A very good solution (IMO) for this problem is to use some kind of template library. One popular option would be Mustache , which has libraries for many languages including JavaScript .
The template approach consists of writing your HTML with placeholders in, for example, the <script> :
<script id="bookmark-template" type="text/html"> <img name="bo_im" class="bookmark_image" src="{{favicon}}"> <a target="_blank" name="bookmark_link" class="bookmark_link" href="{{url}}" id="{{id}}"> {{title}} </a> </script>
Then, when it comes time to render dynamic content, you use a template and provide data to populate it as follows:
var template = document.getElementById("bookmark-template").textContent; var html = Mustache.render(template, bookmark_object);
To illustrate this more clearly, here is a jsFiddle demonstrating this approach (including the advantage of escaping).
There are at least a few advantages to this:
- Using the template allows you to write HTML files with indentation, formatting, etc., to make it as readable as possible, and not just "almost just copy it," as you say in your question. You do not need to write one large line or concatenate a bunch of lines with
+ or even use + . - A good template library will correctly delete your HTML for you.
For me, these advantages are enough. You may feel different.
source share