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?