javascript - 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 provide template:

var data = {   message: 'are sure?' }; 


compile template , append container:
$container.prepend(_.template($("#example-template").html())(data));


approach have written above (from: https://stackoverflow.com/a/7230755/83916) works well, don't if statements in <% if (typeof(headline) !== "undefined") { %>. when write <% if (headline) { %>, headline undefined.

is there more simple way check if variable exists using lodash templates not clutter html?

trying access undefined variable in javascript result in exception unless use typeof. there no real way around that.

however, if wrap whole template in object, using if way want should work (as property missing on object results in undefined, not exception):

var data = {   data: {     message: 'are sure?'   } }; 

and in template:

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

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -