1

所以我使用 Handlebars 来模板化一个静态 HTML 网站。

我遇到的问题是在数据对象中缩进 HTML copyright。如果我在对象中有多个 h1,我希望能够很好地格式化它,就像在我的示例中一样。

尝试缩进数据对象中的 HTML 时,我在控制台中收到语法错误: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>

4

2 回答 2

2

我认为最好将 html 标签添加到模板中,因此在这种情况下,您可以添加到copyright字符串并each像这样在模板中使用

$(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>

于 2015-11-04T16:35:34.547 回答
1

正确的多行格式:

var copyright={
    "copyright":"\
    <h1>This is heading 1</h1>\
    <h1>Another heading indented</h1>\
    "
};

或更好:

var copyright={
    "copyright": "<h1>This is heading 1</h1>" +
    "<h1>Another heading indented</h1>"
};
于 2015-11-04T16:33:17.947 回答