Take the 2-minute tour ×

i am trying to use underscore.js template method to render some data so basically this is what i want to do if i were to do it in pseudo code

if (url is not null) {
       <img src=url />

I need to do this check in underscore js template, but I am not sure if the following is legit the tricky part is that url is also a template variable

<% if (<%=url%>) { %>
    <img src=<%=url%> />
<% } %>


share|improve this question
Remember that the variable MUST be in the context! If you're not always providing "url" when rendering the template you have to check for typeof url !== "undefined" as well. –  Jan Sommer Oct 1 '12 at 19:51
add comment

1 Answer

up vote 3 down vote accepted

On javascript:

 var myTmpl = _.template(foo);
 myTmpl.tmpl({url: 'foo.com'});

On template:

<% if (url) { %>
  <img src=<%=url%> />
<% } %>

Remember: When you use <% you are just writing javascript ;)

share|improve this answer
add comment

Your Answer


