Search code examples
htmlparsingtemplatesbackbone.jsduplicates

Id duplicates when using templates in parse / backbone / js / html


I get duplicate ids when I set the views like so in my render function

var template = _.template($("#user-login-template").html(), {});
this.$el.html(template);

The html looks like this after running the render function, before runing the render function. Beforehand, the <div class ="app"> is empty (as it should be). It copy pasted the code from template and therefore the ids into the div.

<div class="app">
<input type="text" id="signup-username" placeholder="Username"/>
<input type="password" id="signup-password" placeholder="Create a Password"/>                                                                                                                                                              
<button id="signUpBtn">Sign Up</button>
<button id="logInBtn">Login</button>
</div>
<!-- Templates -->
<!-- Login Template -->
<script type="text/template" id="user-login-template">
    <input type="text" id="signup-username" placeholder="Username"/>
    <input type="password" id="signup-password" placeholder="Create a Password"/>
    <button id="signUpBtn">Sign Up</button>
    <button id="logInBtn">Login</button>
</script>

For reference, this is what my whole view looks like

var LogInView = Parse.View.extend({
    el: '.app',
    events: {
        "click .signUpBtn": "signUp",
        "click .logInBtn": "logIn"
    },
    initialize: function (){
        this.render()
    },
    logIn: function () {
        //To Do
    },
    render: function () {
        var template = _.template($("#user-login-template").html(), {});
        this.$el.html(template);
    }
});

Solution

  • If Webstorm is complaining about the ids inside the <script> then it is wrong and you have three options:

    1. Get a new IDE that has a better understanding of HTML.
    2. Figure out how to reconfigure Webstorm to know what HTML really is. There must be a way to beat some sense into Webstorm, this sort of thing is very common these days.
    3. Ignore the warnings (yuck).

    Things inside <script> are not HTML and are not part of the DOM. Ask the browser what $('input[type=text]').length is after your template is rendered and you'll get 1 since the

    <input type="text" id="signup-username" placeholder="Username"/>
    

    inside the <script> isn't HTML, it is just text. You can even check the HTML specification of <script>:

    Permitted contents
    Non-replaceable character data

    Non-replaceable character data is not HTML, it is just text.