How to use underscore/javascript templates in ASP.Net MVC views - asp.net-mvc

I was just wondering how you use the underscore templates in a .aspx view since the <%= %> tags that underscore uses get picked up by the .aspx rendering engine and give me errors.
For instance:
<script type="text/template" id="my-template">
<span class="event" title="<%= description %>">
<%= title %>
</span>
</script>
This template gives me an error since the .aspx rendering engine thinks I'm trying to bind this stuff to the Model.
Thanks.

From the fine manual:
template _.template(templateString, [data], [settings])
[...]
If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string.
So if the default <%=...%>, <%-...%>, and <%...%> delimiters aren't working for you then you can use different ones with a simple configuration change. For example, if you wanted to use {%...%} instead of <%...%>, then do this after underscore.js is loaded and before you use _.template:
_.templateSettings = {
interpolate: /\{%=(.+?)%\}/g,
escape: /\{%-(.+?)%\}/g,
evaluate: /\{%(.+?)%\}/g
};
Demo: http://jsfiddle.net/ambiguous/TfB5M/

Related

How to pass data- attribute to #Html.CheckBoxFor [duplicate]

Is there a nicer syntax when creating elements with hyphenated attributes instead of using:
<%= Html.TextBox ("name", value, new Dictionary<string, object> { {"data-foo", "bar"} }) %>
Looking at the HTML specs for the proposed standards HTML 5 and WIA ARIA it seems hyphens in HTML attributes are being planned to be more common as some sort of simple name spacing.
E.g. HTML 5 proposes custom attributes are prefixed with data- and WIA ARIA uses the aria- prefix for all WIA ARIA attributes.
When using HTML helpers in ASP.NET MVC such as <%= Html.TextBox("name", value, new { attribute = attributeValue }) %> the anonymous object is converted to a dictionary.
Unfortunately in C# there is no support for hyphens in names, so the only alternative is to create a dictionary. The syntax for which is very verbose, has anyone seen a nicer alternative or a simple way of altering the functionality of ASP.NET MVC's HTML extensions without having to re-write the entire extension?
Use an underscore in the data attribute name, and it'll magically handle it for you, converting it to a hyphen. It knows you want a hyphen rather than an underscore as underscores aren't valid in html attribute names.
<%= Html.TextBox("name", value, new { #data_foo = "bar"}) %>
The answer provided at ActionLink htmlAttributes suggests using underscores instead of hyphens. MVC.Net is supposed to emit hyphens instead of the underscores when sending the page to the browser.

Reflection and thymeleaf

I use spring boot and thymeleaf. I have many entity and I need to create crud ui. All ui will be similar Is it possible to use reflection to reduce ui to generate?
I would like to loop on the fields and get value in the thymeleaf template
In these days I have been working on an issue very similar to yours.
I have discovered that Thymeleaf has this thing called preprocessing which allows you to have nested expression, so something like this works:
<p th:text="${__${'myObj.myField'}__}"></p>
In this situation, the expression __${'myObj.myField'}__ is evaluated first: after this preprocessing, the expression that will be evaluated by the <p> tag will become:
<p th:text="${myObj.myField}"></p>
Which is the desidered result. Note that, in the preprocessed expression, we are passing the field as a string: therefore, it should be totally possible to create a fragments with a th:each in it which accepts a list of strings in which each string is a field. This list could either be injected directly in the model through Java or could be statically declared in the Thymeleaf's markup. An example of such fragment could be:
<div th:fragment = "show-details">
<tr th:each = "field : ${fieldsToPrint}">
<td th:text = "${__${myObj + '.' + field}__}"></td>
</tr>
</div>
Which could, for example, be used like this:
<div th:replace = "myfragments :: show-details(fieldsToPrint = ${ {'name', 'surname'} }, myObj = ${objFromModel})"></div>
The list of fields could either be generate manually or through Java reflection.
This procedure still involves some work, but way less than creating by hand all the views, especially if you can show all the entities with the same show-details fragments. I have not got around to it yet, but it should be possible to use a similar pattern also for editing such entities.

Razor, shortest conditional block

I frequently use code like:
<p #if(Model.Sth)
{
?:style="display: none;"
}>Some text</p>
Many template engines have special markers for conditional blocks, for example in Mustache you can write:
<p {{#Model.Sth}}style="display: none;"{{/Model.Sth}}>Some text</p>
Can my Razor code can be written in shorter form?
In Razor you can embed expressions inside parenthesis to execute them inline. If your conditional can be written using the ternary operator, then you can do something like this:
#(this.Model.Sth ? "style='display:none;'" : string.Empty)
The trick is getting Razor to emit the resulting string correctly back into your HTML. You could use HtmlHelper to do it, but it gets messy enough that the long-form conditional is much cleaner.
In the specific case of an attribute, however, there's a special feature of Razor, as of MVC4, that will help. If you specify an attribute using an expression that evaluates to null, MVC won't emit the attribute at all, so you can do:
<p style="#(this.Model.Sth ? "display:none;" : null)">Some Text</p>
(Note that null and string.Empty are different in this case: Razor will emit style="" if your expression evaluates to empty string.)

Rails erb vs gsub dynamic template performance

In my project, I am using the ERB as template engine. We have one page which used ERB template and it's loaded within 5-7 seconds.
The same page we changed it into dynamic template, the template values are stored in the database.
sample template
<p> {{name}} </p>
<p> {{address}} </p>
<p> {{mobile number}} </p>
For applying the actual values over dynamic template, i have used the gsub. This case the same page takes load time as 16-20 seconds. I used 17 gsub over dynamic template.
How erb rendering is fast? (Because i am using the same content
before and after dynamic template)
Is there any way to increase the performance?
Note:
Compared to 'gsub' method, 'sub' method is fast. But in my case i need to use global sub (gsub).
In my case, the whole page is like a dynamic template with 20 tags. In that case gsub is not a correct solution to replace the 20 tags.
Client Side:
I have used the client side template engine called Handlebar.js. Using this my page loads with normal speed.
Server Side:
https://github.com/Shopify/liquid
If you store templates in database then you could use appropriate tools to render them. If it's erb then just use ERB, don't gsub variables manually. The reason why erb is so much faster than manual gsub is because erb template gets compiled to ruby code (like "Foo <%= bar %>" becomes "Foo " + bar) and executed.
As I understand you want to store your templates in database and render them both on server and client. You can use mustache for that, it's framework-agnostic and safe to run on server.

Ruby/Rails - Parsing and Displaying HTML from a Models Attribute

I have a Rails Model called Events which has as field/attribute called :description.
I migrated it under the type t.text rather than t.string since I was going to be displaying a large amount of data.
So.... Now I'm at the point where I would like to display <%= #event.description %> in a neat way and would like to break up some of the sentences rather than one large block of information.
I was hoping I could insert <p> or other html codes to help with how the text is displayed.
The problem is inserting <p> into the field only prints <p> and the not desired action of the html command.
How can I add html styling to the text attribute?
You can use <%=raw #event.description %> to echo unescaped content. Be aware that this is a potential XSS security hole, if users can ever affect that content. I highly recommend using the sanitize helper to strip out any unwelcome markup before you write it out.
It strictly depends on how you print it. In particular, if you print with calling h function (<%= h my_text =>), output will be sanitized and html escaped.
It may also depend on your rails version: I've head in Rails 3 html is escaped by default, even if you don't use h.

Resources