Node js html template

Основы шаблонов

Шаблон — это текстовый файл, определяющий структуру, или внешний вид выходного файла, с предусмотренными позициями, в которые будут помещаться данные при отображении по шаблону (в Express шаблоны также называют представлениями).

Выбор шаблонов Express

В Express можно использовать много движков отображающих шаблонов ( template rendering engines). В этом руководстве для шаблонов будет использован Pug (ранее известный как Jade) . Это наиболее популярный в Node язык шаблонов, который о себе заявляет так: чистый, чувствительный к пробелам синтаксис для написания HTML, на который сильно повлиял Haml.

Разные языки шаблонов используют различные подходы для определения внешнего вида и разметки позиций для данных—некоторые используют HTML для определения внешнего вида, тогда как другие применяют различные форматы разметки, которые затем должны компилироваться в HTML. Pug — второго типа; он использует представление (representation) HTML, в котором первое слово в каждой строке обычно представляет элемент HTML, а отступы в следующих строках применяются, чтобы представить вложенные элементы. Результатом является определение страницы, которое транслируется непосредственно в HTML, и которое, вероятно, более краткое и легче читается.

Примечание: недостаток применения Pug — это чувствительность к отступам и пробелам (если добавить лишний пробел в «плохом» месте, можно получить невразумительный код ошибки). Однако, если ваши шаблоны уже действуют, их очень легко читать и поддерживать.

Конфигурация шаблона

Когда создавался каркас (the skeleton website) веб-сайта LocalLibrary, он был настроен на использование Pug . Можно было заметить, что модуль pug включён в зависимости в файле package.json, и установлен (app.set(. )) как движок представлений в файле app.js. Эта установка показывает,, что движок представлений — pug, и что Express должен искать шаблоны в подкаталоге /views.

// View engine setup. app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); 

Если посмотреть содержимое каталога views, можно увидеть файлы с расширением .pug, в которых шаблоны представлений по умолчанию. Это представление для домашней страницы (index.pug) и базовый шаблон (layout.pug), который следует заменить нашим содержимым.

/express-locallibrary-tutorial //the project root /views error.pug index.pug layout.pug

Синтаксис шаблонов

Пример файла шаблона (ниже) демонстрирует многие наиболее полезные черты Pug.

Читайте также:  Time delay on python

Сначала отметим, что файл отражает структуру типового HTML-файла, причём первое слов в (почти) каждой строке является элементом HTML, а отступы используются, чтобы показать вложенные элементы. Так, например, элемент body находится внутри элемента html , а элементы p (параграфы) — внутри элемента body, и так далее. Невложенные элементы (т.е. индивидуальные параграфы) располагаются в отдельных строках.

em> is emphasisedem>'> and escaped data: #em> is not emphasisedem>'>. | This line follows on. p= 'Evaluated and em>escaped expressionem>:' + title // You can add single line JavaScript comments and they are generated to HTML comments //- Introducing a single line JavaScript comment with "//-" ensures the comment isn't rendered to HTML p A line with a link a(href='/catalog/authors') Some link text | and some extra text. #container.col if title p A variable named "title" exists. else p A variable named "title" does not exist. p. Pug is a terse and simple template language with a strong focus on performance and powerful features. h2 Generate a list ul each val in [1, 2, 3, 4, 5] li= val 

Атрибуты элементов определены в скобках после соответствующих элементов. В скобках располагается список пар *имя атрибута=значение,*причём элементы списка разделяются запятой или пробелом. Например:

  • script(type=’text/javascript’) , link(rel=’stylesheet’, href=’/stylesheets/style.css’)
  • meta(name=’viewport’ content=’width=device-width initial-scale=1′)

Значения всех атрибутов экранируются (т.е. такие символы как » > » заменяются эквивалентными кодами HTML как » >» ) , чтобы предотвратить JavaScript инъекции и межсайтовые атаки.

Если после тэга стоит знак = , следующий текст рассматривается как выражение JavaScript. Например, ниже в первой строке, содержимое тэга h1 будет переменной title (которая определена в файле или передана в шаблон из Express). Во второй строке содержимое параграфа — это текстовая строка, соединённая с переменной title . В каждом из случаев поведение по умолчанию — экранировать строки.

em>escaped expressionem>:' + title 

Если после тэга знак = отсутствует, тогда содержимое рассматривается как обычный текст. Внутри текста можно вставить экранированные или неэкранированные данные, применяя синтаксис #<> и !<> , как показано ниже. В простой текст можно также вставлять «сырой» HTML.

em> is emphasisedem>'>, an escaped string: #em> is not emphasisedem>'>, and escaped variables: #. 

Примечание: Почти всегда желательно экранировать данные, полученные от пользователей (при помощи синтаксиса #<> ). Данные, которым можно верить (т.е. подсчитанное количество записей, могут быть выведены без экранирования значений.

Можно использовать символ конвейера (‘|‘) в начале строки, чтобы отметить простой текст («plain text»). Например, дополнительный текст, приведённый ниже, будет показан в той же строке, что и предыдущий, но не будет относиться к ссылке.

Можно также выполнять циклы (итерации), применяя синтаксис each-in или while . Фрагмент кода (ниже) содержит цикл по элементам массива, чтобы показать список элементов (отметим применение ‘li=’ для оценки «val» как переменной). Значение итератора val может быть также передано в шаблон как переменная!

Расширение шаблонов

Принято иметь общую структуру для всех страниц сайта, включая стандартную HTML-разметку для заголовка, футера, навигации и т.д. Вместо того, чтобы заставлять разработчиков дублировать эти образцы на каждой странице, Pug позволяет объявить базовой шаблон, а затем модифицировать его, заменяя только те небольшие части, которые различны на каждой конкретной странице.

Например, базовый шаблон layout.pug, созданный в каркасе проекта, имеет такой вид:

Next steps

Found a content problem with this page?

This page was last modified on 11 февр. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

HTML Templating in NodeJs

HTML templating is a technique that allows us to create a base HTML structure and use placeholders to dynamically generate content based on data retrieved from our JSON file or database. Let’s consider a hypothetical instance where our website consists of numerous product cards, each containing specific product details that are retrieved from the JSON file. Now, if we were to add or remove any products from our JSON file, how would we update the corresponding cards on the front-end dynamically? Considering our content-based data is stored in a JSON file, we can proceed with creating reusable templates from our existing HTML code. Step 1: Building the templates
As a developer, you’re probably familiar with the concept of serving dynamic web content. One way to achieve this is by using templates. We would create two HTML templates, one for the product overview page and one for the individual product cards. The first template template-card.html is used as a blueprint for the individual product cards, and the second template-overview.html is used as a blueprint for the overview page. These templates contain placeholders that will be replaced with actual content when the page is requested by a user. Ensure that your placeholder does not contain any symbols that are part of the HTML code. A commonly used syntax for placeholders is . Here is template-card.html our first template used as a blueprint to create as many cards as needed dynamically.

 
Organic!
per 📦
"> Detail 👉

As this card will serve as a template, the information contained within it should be replaced with placeholders as well. Once the placeholders have been added, the card will resemble the following:

 
🥦🥦

Apollo Broccoli

Organic!
3🥦 per 📦
5.50€
Detail 👉

The anchor tag contains an href link that includes a placeholder for an ID. This indicates that each card or product in our JSON file has a distinct ID. These IDs are unique and will be utilized in identifying each product during routing. Also, when we need to style elements based on their category, CSS classes and IDs can be substituted with placeholders as is done in the image examples. This approach can prove especially useful in such cases.

In this example, we have substituted our template card with a placeholder. It’s important to keep in mind that we will generate multiple cards dynamically using this single template card. Note: This is our second template card, template-overview.html Step 2: Filling the templates
Here comes the fun part, filling our templates by replacing our placeholders with actual content. When a user requests a URL, the code reads the relevant template file (either template-overview.html or template-card.html ) synchronously, fills it dynamically with content from a JSON file, and sends back the relevant content as a response to the user. This is achieved through the use of the replaceTemplate function, which replaces the placeholders in the template with actual content.

// SECOND STEP: const replaceTemplate = (temp, product) => < let output = temp.replace(//g, product.productName); output = output.replace(//g, product.image); output = output.replace(//g, product.price); output = output.replace(//g, product.id); // /g is a regex global flag return output; > // FIRST STEP: const tempOverview = fs.readFileSync(`$/templates/template-overview.html`, 'utf-8'); const tempCard = fs.readFileSync(`$/templates/template-card.html`, 'utf-8'); const data = fs.readFileSync(`$/dev-data/data.json`, 'utf-8'); const dataObj = JSON.parse(data); // THIRD STEP: const server = http.createServer((req, res) => < const pathName = req.url; //FOURTH STEP: //Here is the Overview if(pathName === '/' || pathName === '/overview') < res.writeHead(200, ); const cardsHtml = dataObj.map(el => replaceTemplate(tempCard, el)).join(''); const output = tempOverview.replace(' else if(pathName === '/api') < res.writeHead(200, ); res.end(data); // Not Found > else < res.writeHead(404, < 'Content-type': 'text/html', //standard header 'my-header': 'hello-world' >); res.end('

This page cannot be found.

'); > >); server.listen(8000, '127.0.0.1', () => < console.log('Listening to requests on port 8000'); >); res.writeHead(404, < 'Content-type': 'text/html', //standard header 'my-header': 'hello-world' >); res.end('

This page cannot be found.

'); > >); server.listen(8000, '127.0.0.1', () => < console.log('Listening to requests on port 8000'); >);
  • First, read the two HTML template files and the product data that is stored in a JSON file
  • Second, define a function that replaces placeholders in the templates with product-specific data. Here, our function is named replaceTemplate
  • Third, listen to incoming HTTP requests and check the pathname of the request URL
  • Fourth, If the pathname is / or /overview , generate HTML code for each product card by replacing placeholders in the tempCard template using the replaceTemplate function and the product data from the JSON file.
  • The resulting HTML for each card is then concatenated to create the cardsHtml string. The tempOverview template is then modified to include the cardsHtml string and the resulting HTML code is sent back as the response.
  • Also, if the pathname is /api it sends back the product data in JSON format as the response
  • Finally, if the pathname is anything else, sends back a 404 error message.

Wow, that code did look like a lot, but if we look closely and take it one step at a time, it’s not that complicated.

All it’s doing is replacing some special words with real information and sending it back to the website so people can see it!

Benefits of HTML templating
HTML templating offers several benefits that make it a popular choice among web developers:

  • By utilizing HTML templating, we separate content from the presentation allowing developers to generate reusable templates that can handle varying amounts of data from multiple sources, and maintain multiple copies of similar code.
  • HTML templates provide a standard structure for presenting data, improving user experience and easy navigation on the site.
  • The flexibility of templating makes it easier to modify the underlying data. This saves time and effort, as developers don’t need to change the HTML code manually.
  • Since HTML templates are reusable, they are easier to maintain and update. Changes to the underlying data can be made without modifying the template code, which reduces the likelihood of errors.
  • HTML templating can handle large amounts of data without compromising performance. This makes it an ideal choice for websites with a significant amount of dynamic content.

In summary, HTML templating is an efficient, consistent, flexible, and scalable technique that simplifies the development and maintenance of dynamic web content.

By separating content from presentation, HTML templating enables developers to create reusable templates that can handle varying amounts of data, without having to hard-code the content into each page.

Bonus Section:
There are several other templating engines available in Node.js, such as EJS, Pug (formerly known as Jade), Handlebars, and Mustache, among others.

To use a templating engine in Node.js, you’ll need to install it via npm and then require it in your code. These engines provide a way to generate HTML by inserting data into placeholders within the template.

You’ve reached the end of the article! 🎉 Hope you enjoyed this post and learned something new 💡.
Thanks for sticking around.

Источник

Оцените статью