O
O
olegkurbatov2017-05-23 18:02:00
JavaScript
olegkurbatov, 2017-05-23 18:02:00

How to correctly build a whole block on a page using javascript?

I'm pulling info from json file.
I put it on the site like this:

news.forEach(function(news) {
            var article = document.createElement('article');
            article.className = "block-news__news";
            article.innerHTML = '<span><h2 class="block-news__header">'+news.header+'</h2><time class="block-news__date">'+news.date+'</time></span><p id="'+news.preId+news.id+'">'+news.content+'</p><a class="block-news__more" id="'+news.id+'" href="#">more ></a>'

            divNews.insertBefore(article, divNews.children[1]);
        });


But this innerHTML line is very unreadable... I don't understand how to do it otherwise. How to "paint" the structure of this block in a normal way?

how to fix this ugliness?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Egor Zhivagin, 2017-05-23
@Krasnodar_etc

news.forEach(function(news) {
            var article = document.createElement('article');
            article.className = "block-news__news";
            article.innerHTML = '
                              <span>
                                  <h2 class="block-news__header">'+news.header+'</h2>
                                  <time class="block-news__date">'+news.date+'</time> 
                              </span>
                              <p id="'+news.preId+news.id+'">'+news.content+'</p>
                              <a class="block-news__more" id="'+news.id+'" href="#">more ></a>'

            divNews.insertBefore(article, divNews.children[1]);
        });

It will work, right?)

A
Alexey Nikolaev, 2017-05-23
@Heian

In a similar situation, I connected haml-js. All markup was stored in haml-templates on the server side. Next, I loaded the haml template using $.load, passing it a set of data for rendering by the haml engine itself, and after rendering, I displayed the received data.
Unfortunately, I can’t throw off the code due to the prescription of cases, but I suggested the algorithm to you. Beautiful, clean, without ugliness. A clear disadvantage - speed - can be easily eliminated using some kind of localStorage: then the template will have to be downloaded from the server only once.

O
olegkurbatov, 2017-05-23
@olegkurbatov

content; a.innerHTML = 'more >';
a.href = '#';
divNews.insertBefore(article, divNews.children[1]);
article.appendChild(span);
span.appendChild(h2);
span.appendChild(time);
article.appendChild(p);
article.appendChild(a);
});
Sawed, it will be better, but is it right?

R
RidgeA, 2017-05-23
@RidgeA

Here I can advise another template engine for the client
basisjs.com/templates Fast
enough and with binding.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question