How to set up variables inside an underscore.js
template for an app built with backbone.js
? I just want to create reusable processed strings. Also, can underscore.js
's built-in functions like _.escape
be used to process those variables?
<script type="text/html" id="templateresults">
<p><%= encodeURIComponent(title) %></p> // this works
// try 1:
var encodedTitle = encodeURIComponent(title); // shows up as regular text
<p>'+encodedTitle+'</p> // this doesn't work and shows up as regular text
// try 2:
<% var encodedTitle = encodeURIComponent(title); %> // nothing shows up
<p><% '+encodedTitle+' %></p> // nothing shows up
</script>
title
is a JSON item (text string).
Encoded output: This%20is%20a%20Sample%20Title
Regular output: This is a Sample Title
Naming variablesAfter the first letter, you can use numbers, as well as letters, underscores, or dollar signs. Don't use any of JavaScript's reserved keywords.
What is this? In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.
The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources.
Your try 2 is almost right but the tag where you output encodedTitle is missing the =
at the start and doesn't need the +
in the string. Should be:
<p><%= encodedTitle %></p>
Alternatively you could also do:
<p><% print(encodedTitle) %></p>
In underscore templates, any javascript you want evaluated must be contained inside <% %>
, hence why your second attempt just outputs the the javascript as a string. You correctly used the =
in your sample at the top but omitted it in try 2.
The =
tells the templating engine to output the result of the enclosed javascript as a string. If you don't use the =
, the javascript is executed, but nothing is output. Underscore's templates provide the print()
function as an alternative to using the =
, I dont know that one way is better than the other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With