Chalist
Chalist

Reputation: 3309

Underscore.js - Condition in template

I have a model with this fields:

I would like to show url when title is empty. for this I write:

<%= if(feed.get('title') == ''){ %>
    <%= feed.get('url') %>
<%= }else{ %>
    <%= feed.get('title') %>
<%= } %>

but I got error.

How I can do this?

Upvotes: 0

Views: 85

Answers (3)

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

This might be of some help while practising underscore's templates, a simple Underscore Template Editor.

Upvotes: 1

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14225

<% if (feed.get('title') === '') { %>
    <%= feed.get('url'); %>
<% } else { %>
    <%= feed.get('title'); %>
<% } %>

From underscore source:

evaluate    : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape      : /<%-([\s\S]+?)%>/g

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47172

It's because your syntax is wrong.

<%= %> outputs things to your page.

When you want to execute javascript code you use <% %>. And if you want to escape your HTML, you use <%- %>.

So your code should be

<% if(feed.get('title') == '' %>
    <%= feed.get('url') %>
<% }else{ %>
    <%= feed.get('title') %>
<% } %>

Upvotes: 3

Related Questions