Barun Sharma
Barun Sharma

Reputation: 1468

Better way to use a variable in html

I wanted to have a template which would be used to create dynamic user detail forms. But I need to have different ids for all elements, so as to post the details correctly. My template looks like:-

<div id="user-template" class="hidden">
    <div class='lbl-div' id='user(user_number)'>
        <label>User(user_number)</label>
    </div>
    <label class="lbl" id="user(user_number)_firstname">Firstname:</label>
    <input type="text" value="" />
    <label class="lbl" id="user(user_number)_lastname">Lastname:</label>
    <input type="text" value="" />
</div>

Here, user_number is a variable. onclick of a button would pick this template-->replace user_number with a global variable-->increment the global variable-->append the modified template as a child to the parent div.

I replace the variables as:-

template = template.replace(/\(user_number\)/g, count);
count++;

Here count is the global variable.

Is there a better way to achieve this(using the template dynamically with changing ids)?

Upvotes: 1

Views: 101

Answers (1)

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

If you are using html templates, then try using any templating engine, like underscore, mustache. But templating engine will not give you two way binding between template and your data. It just render template with given data.

If you want to use pure two way databinding application, then try using web application frameworks like angularjs or emberjs.

Upvotes: 2

Related Questions