how to reuse HTML structure and change content (avoid Ctrl c Ctrl v)

Asked

Viewed 218 times

0

div {
  display: flex;
  flex-direction: row;
  flex:1;
  
  justify-content: center;
  align-items: center;
}

img{
  margin: 10px 0;
}
<div>
  <section>
    <h1>Titulo 1</h1>
    <p> alguem paragrafo de descrição 1 </p>

    <ol>
      <li> item 1</li>
      <li> item 2</li>
      <li> item 3</li>
    </ol>
  </section>
  <img src="https://i.pinimg.com/236x/ae/6f/0c/ae6f0c06031ec9671943bd8be104955f.jpg" width="300px">    
</div>

<div>
  <section>
    <h1>Titulo 2</h1>
    <p> alguem paragrafo de descrição 2 </p>

    <ol>
      <li> aaa </li>
      <li> aaa </li>
      <li> aaa </li>
    </ol>
  </section>
  <img src="https://www.mentebinaria.com.br/uploads/monthly_2018_02/large.enduser.jpeg.bba8c1fc675d79f4498627eef97fef92.jpeg" width="300px">    
</div>

<div>
  <section>
    <h1>Titulo 3</h1>
    <p> alguem paragrafo de descrição 3 </p>

    <ol>
      <li> ronaldo </li>
      <li> romero brito </li>
      <li> kugo stozo </li>
    </ol>
  </section>
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR21uPpWezBvq5pq8wBWN3led17DmF0YTIKsUraGaxbaFyUah8d" width="300px">    
</div>

<div>
  <section>
    <h1>Titulo 4</h1>
    <p> alguem paragrafo de descrição 4 </p>

    <ol>
      <li> amarelo </li>
      <li> azul </li>
      <li> vermelho </li>
    </ol>
  </section>
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3B6n6DyBqzVZeKgMgceAkL7aoosSLgI6NYG4djCFjKSnxJRWlBA" width="300px">  
</div>

first excuse Newbie’s question but I really did not find a satisfactory answer on Mr. google.

so I have a chunk of code that has 4 Divs that follow the same pattern, but with different content, like reuse this same structure and add 4 Divs, without using one (Ctrl c Ctrl v), the goal here and decreases the amount of lines in the html file.

  • You want to do it in the browser or on the server?

  • what’s the difference? I think q in the browser.

  • I suggest you do it where you have the contents for those records. If you have it in the database it seems more logical to me on the server, but depending on the usage... there are pros and cons... what language do you have on the server? where you have that data?

  • <template> + json = . Anything I can post an example based on the posted structure.

  • Yes, at the moment only on my computer, I am studying.

  • @Valdeirpsr if it is not to give work brother, put there :)

  • The @Sergio example already helps. :)

Show 2 more comments

2 answers

2


Sort this content in an object array. Something like this:

[{
  titulo: 'Jogadores',
  descricao: 'Os melhores jogadores do mundo',
  items: ['Ronaldo', 'Messi']
},
{
  titulo: 'Cores',
  descricao: 'Cores intressantes',
  items: ['Azul', 'Amarelo']
}]

And then you can have a piece of HTML as "shape" to generate HTML with Javascript:

const conteudo = [{
    titulo: 'Jogadores',
    descricao: 'Os melhores jogadores do mundo',
    items: ['Ronaldo', 'Messi'],
    img: 'https://thumbs.dreamstime.com/z/grupo-de-summer-games-icon-do-atleta-do-jogador-de-futebol-atleta-isom%C3%A9trico-do-jogador-de-futebol-d-olympics-que-ostentam-73533395.jpg'
  },
  {
    titulo: 'Cores',
    descricao: 'Cores intressantes',
    items: ['Azul', 'Amarelo'],
    img: 'https://cdn0.iconfinder.com/data/icons/office-2-9/48/81-512.png'
  }
];

const template = document.querySelector('template');

conteudo.forEach(obj => {
  const clone = document.importNode(template.content, true);
  clone.querySelector('h1').textContent = obj.titulo;
  clone.querySelector('p').textContent = obj.descricao;
  clone.querySelector('ol').innerHTML = obj.items.map(item => `<li>${item}</li>`);
  clone.querySelector('img').src = obj.img;
  document.body.appendChild(clone);

});
<template>
  <div>
    <section>
      <h1></h1>
      <p></p>
      <ol></ol>
    </section>
    <img src="" width="300px">    
  </div>
</template>

0

Question:

  1. Optimization of code writing in the front end:

    That being the problem, the best solution is to use a template engine, allowing the use of a static file - read template, which you can replace "dynamically" values of variables defined in your template.
    There are several Engines templates in the market, among them I can mention the best known: Pug, Handlebars, Mustache.

  2. Handle Back-end Dynamic Data

    In this scenario you make use of a dynamic language that treats this data on the side Server-side and delivers text content to the browser. Today you can already count on Javascript for this type of work, using Node and some Server module like Express, that can handle requests and response efficiently.
    The interesting thing is that you can work with a template engine in this scenario too, thus being what before it was only possible to do with languages like PHP and others, as:

    • Manipulating data from the database
    • Dynamically generate iteration loops over this data
    • Treat this data, how to perform some calculation for example

In short optimization or handling dynamic data, the important thing is to understand the scenarios and know in fact what is intended to do.


Codepen: I left an example of code using template engine here

Code snippet

Obs: Note that when executing the code below, the interpreter will not parse code using syntax template engine, in case the Pug. Yet this is a dynamic code on the front end

- const thinkers = [{name:'carl gustav jung', field:'psychiatry', work:['the archetypes and the collective unconscious','on the nature of the psyche',''], thought:'Tudo que nos irrita nos outros pode nos levar a um melhor conhecimento de nós mesmos.'},{name:'aristóteles', field:'philosopher', work:['de Interpretatione','analytica Priora','de sophisticis elenchis'], thought:'Sábio é aquele que conhece os limites da sua própria ignorância.'}]
- const musicians = [{name:'john Coltrane', style:'jazz', discography:['blue train','soultrane','a love supreme'], bio:'Biography...'},{name:'miles davis', style:'jazz', discography:['tutu','in a silent way','miles ahead'], bio:'Biography...'}]
section.bl-content
  each data,ind in thinkers
    article.bc-featured
      h2.bc-featured__title= data.name
      p.bc-featured__paragraph= data.thought
      ul.bc-featured__list
        each item,ind in data.work
          li.bc-featured__item= item
section.bl-content          
    each data,ind in musicians
      article.bc-featured
        h2.bc-featured__title= data.name
        p.bc-featured__paragraph= data.bio
        ul.bc-featured__list
          each item,ind in data.discography
            li.bc-featured__item= item
  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.