1

The scenario is quite common, you have a container div and some html to append inside the container:

for ( var i = 0; i < 5; i++ ) {
    $('.container-list').append('<div class="item">ITEM ' + i + ' </div>');
}

Example: http://jsfiddle.net/55og08za/

The html to append is dynamic, so there are certain parts of it that changes. The code works, but is very ugly and difficult to maintain if the html is long, mixing html inside javascript is not the best. Also as the content is dynamic I can have a field with quotes or special chars that will break my code, so yes, I will need to escape the strings before, but as you go the code just become more and more ugly.

Is there a way to clean this up maybe with a more object oriented approach?

1 Answer 1

1

What about simple templating solution? Using template will make your code much more flexible. For example one approach:

// .. or define template as a function template() { ... }
String.prototype.template = function(data) {
    return this.replace(/\{\{(.+?)\}\}/g, function(a, b) {
        console.log(b)
        return typeof data[b] !== 'undefined' ? data[b] : '';
    });
};

var item = document.getElementById('item').innerHTML;

for ( var i = 0; i < 5; i++ ) {
    $('.container-list').append(item.template({
        text: 'Item',
        index: i
    }));
}
.container-list {
    background-color: #eee;
    height: 300px; 
}
.item {
    background-color: #666;
    height: 30px;
    margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-list"></div>

<script type="text/template" id="item">
    <div class="item">{{text}} {{index}}</div>
</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.