So I'm using Handlebars to template a static HTML site.
What I am having trouble with is indenting the HTML inside the data object copyright
. If I had multiple h1's in the object, I want to able to format it nicely, like in my example.
When trying to indent the HTML in the data object, I get a syntax error in the console: unterminated string literal
.
$(function() { // Grab the template script var theTemplateScript = $("#address-template").html(); // Compile the template var theTemplate = Handlebars.compile(theTemplateScript); // Define our data object (this one works) var copyright = { "copyright": "<h1>This is heading 1</h1>" }; //////// // This one doesn't work //////// var copyright = { "copyright": " <h1>This is heading 1</h1> <h1>Another heading indented</h1> " }; // Pass our data to the template var theCompiledHtml = theTemplate(copyright); // Add the compiled html to the page $('.content-placeholder').html(theCompiledHtml); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!--This is our template. --> <!--Data will be inserted in its according place, replacing the brackets.--> <script id="address-template" type="text/x-handlebars-template"> <div>{{{copyright}}}</div> </script> <!--Your new content will be displayed in here--> <div class="content-placeholder"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.min.js"></script> <script src="index.js"></script>
I think better put html tags to templates, so in this case you can add to copyright
strings and in template use each
like this
$(function () { var theTemplateScript = $("#address-template").html(); var theTemplate = Handlebars.compile(theTemplateScript); var copyright = { "copyright": [ 'This is heading 1', 'Another heading indented' ] }; var theCompiledHtml = theTemplate(copyright); $('.content-placeholder').html(theCompiledHtml); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.min.js"></script> <script id="address-template" type="text/x-handlebars-template"> <div> {{#each copyright}} <h1>{{this}}</h1> {{/each}} </div> </script> <div class="content-placeholder"></div>
Proper multiline formatting:
var copyright={
"copyright":"\
<h1>This is heading 1</h1>\
<h1>Another heading indented</h1>\
"
};
or better:
var copyright={
"copyright": "<h1>This is heading 1</h1>" +
"<h1>Another heading indented</h1>"
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.