Answer the question
In order to leave comments, you need to log in
Templates in client-side JavaScript. What is the best way to organize in this case?
There is data generated in the js file: json is formed from various things, arrays are processed in a cycle, etc., that is, at the "output" from js, we get data in json.
The data is transferred to html, which also has its own cycle, which does exactly the same thing, but already sorting through the "beautiful" values.
If everything was in the template, in html, the template engine would, in fact, not be needed ... and so - I collect different data, process them in a js-file into json - I give html.
What kills most of all is that in the html file this data is again shoveled ...
Here, in fact, is a good example:
// ...
var el = $('#searchResults')[0],
le = $(el).render().before();
// ...
$.json({
url: url,
params: {
/* some params */
},
success: function(data) {
var data_ = { results: [] };
//////////// Цикл
$.each(data.c.content.webcolors, function(result, i) {
data_.results[i] = {
'title' : result.unicode_title.getText(), // Title
'colorCode' : result.code.web, // Color Code
'desc' : result.text.small_text, // Description
'link' : result.webpage // Link
}
});
data_ = $(el).render(le).now(data_);
data_.replace();
}
});
// ...
<div id="MyColors" type="text/template">
//////////// Снова цикл, перебирает буквально то же самое
<% $.each (f.results, function(r) { %>
<div class="color">
<h3 class="title"><%=r.title%>: <%=r.colorCode%></h3>
<div class="links">
<a class="link"><%=r.link%></span>
<a class="search-link" href="https://www.google.ru/search?q=<%=encodeURIComponent(r.colorCode)%>">
Найти <span style="color:<%=r.colorCode%>"><%=r.title%></span> в Google
</a>
</div>
<div class="description"><%=r.desc%></div>
</div>
<% }); %>
</div>
Answer the question
In order to leave comments, you need to log in
why not use template already in js
especially if you use template string ``?
(() => {
const data = [{
'class': 'news-box',
'title': 'Title 1',
'content': 'Lorem inpsum'
}, {
'class': 'news-box',
'title': 'Title 2',
'content': 'Lorem inpsum'
}, {
'class': 'news-box',
'title': 'Title 3',
'content': 'Lorem inpsum'
},];
const tmpl = (data) => {
return `<div class="${data.class}"><h2>${data.title}</h2><p>${data.content}</p></div>`
};
const rootApp = document.querySelector('#rootApp');
const htmlContent = data.map(el => tmpl(el)).join('');
rootApp.innerHTML = htmlContent;
})();
https://learn.javascript.ru/template-lodash
https://pugjs.org/api/getting-started.html
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question