zeckdude
zeckdude

Reputation: 16163

Using lodash templates, how can I check if a variable exists?

I'm using Lodash templates.


Template:

<script type="text/template" id="example-template">
  <% if (typeof(leadingIconClass) !== "undefined") { %>
    <span class="glyphicon glyphicon-<%= leadingIconClass %>" aria-hidden="true"></span>
  <% } %>

  <% if (typeof(headline) !== "undefined") { %>
    <strong><%= headline %></strong>
  <% } %>

  <%= message %>

  <% if (typeof(mainHTML) !== "undefined") { %>
    <div class="group" style="margin-top: 20px;">
      <%= mainHTML %>
    </div>
  <% } %>
</script>


Data to provide to template:

var data = {
  message: 'Are you sure?'
};


Compile template and append to container:
$container.prepend(_.template($("#example-template").html())(data));


The approach I have written above (from: https://stackoverflow.com/a/7230755/83916) works well, but I really don't like the if statements as in <% if (typeof(headline) !== "undefined") { %>. But when I simply write <% if (headline) { %>, it will say that headline is undefined.

Is there a more simple way to check if a variable exists using lodash templates that will not clutter up the html?

Upvotes: 1

Views: 2396

Answers (1)

fstanis
fstanis

Reputation: 5534

Trying to access an undefined variable in JavaScript will result in an exception unless you use typeof. There is no real way around that.

However, if you wrap your whole template in another object, then using an if the way you want should work (as a property missing on an object results in undefined, not an exception):

var data = {
  data: {
    message: 'Are you sure?'
  }
};

And then in your template:

<script type="text/template" id="example-template">
  <% if (data.leadingIconClass) { %>
    <span class="glyphicon glyphicon-<%= data.leadingIconClass %>" aria-hidden="true"></span>
  <% } %>

...

Upvotes: 2

Related Questions