1

Так что я использую Handlebars для шаблона статического HTML-сайта.Как отступать HTML в объекте данных Handlebars

У меня возникают проблемы с вложением 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>

ответ

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>" 
}; 
+0

Это, как правило, не считается хорошей практикой использовать эту модель из-за непоследовательное поведение среди браузеров и тот факт, что он влезает во время минификации (удаление пробелов). См. [Этот ответ] (http://stackoverflow.com/a/6247331/2502532) на аналогичном SO Q & A. См. Также многочисленные оговорки, упомянутые в комментариях к [этому, к сожалению, принятому отвечу] (http://stackoverflow.com/a/805113/2502532). – gfullam

+0

@gfullam Для HTML парсеров '

и'

\ п

'точно так же. –

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>

+1

Согласен: ваш шаблон Handlebars должен содержать вашу разметку. Ваш JSON должен просто заполнить его данными. – gfullam

Смежные вопросы