# Препроцессор Pug(Jade) Pug - это препроцессор HTML и шаблонизатор, который был написан на JavaScript для Node.js. #### Содержание: 1. [Теги](#Теги) 1. [Текст](#Текст) 1. [Атрибуты](#Атрибуты) 1. [Констуркция Switch Case](#Констуркция-Switch-Case) 1. [Циклы](#Циклы) 1. [Вставка JavaScript кода](#Вставка-JavaScript-кода) 1. [Комментарии](#Комментарии) 1. [Условия](#Условия) 1. [Тип документа](#Тип-документа) 1. [Инклюды (Includes)](#Инклюды) 1. [Наследование шаблонов](#Наследование-шаблонов) 1. [Интерполяция переменных](#Интерполяция-переменных) 1. [Миксины](#Миксины) 1. [Многострочный ассоциативный массив](#Ассоциативный-массив) [Официальная документация по Pug](https://pugjs.org/language/attributes.html) ### Теги В Pug нет закрывающих тегов, вместо этого он использует строгую табуляцию (или отступы) для определения вложености тегов. Для закрытия тегов в конце необходимо добавить символ `/`: `foo(bar='baz')/` Pug ````pug ul li Item A li Item B li Item C ```` HTML ````html ```` ### Текст Непосредственно в Pug можно вставлять элементы в HTML синтаксисе Pug ````pug p This is plain old text content. ```` HTML ```html

This is plain old text content.

```` *** Pug ````pug p | The pipe always goes at the beginning of its own line, | not counting indentation. ```` HTML ````html

The pipe always goes at the beginning of its own line, not counting indentation.

```` ### Атрибуты В Pug можно встраивать JavaScript код, благодаря чему возможны конструкции показанные ниже. Pug ````pug a(href='google.com') Google | | a(class='button' href='google.com') Google | | a(class='button', href='google.com') Google ```` HTML ````html Google Google Google ```` *** Pug ````pug - var authenticated = true body(class=authenticated ? 'authed' : 'anon') ```` HTML ````html ```` *** Pug ````pug input( type='checkbox' name='agreement' checked ) ```` HTML ````html ```` *** Pug ````pug - var url = 'pug-test.html'; a(href='/' + url) Link | | - url = 'https://example.com/' a(href=url) Another link ```` HTML ````html Link Another link ```` *** Pug ````pug - var classes = ['foo', 'bar', 'baz'] a(class=classes) | | //- the class attribute may also be repeated to merge arrays a.bang(class=classes class=['bing']) ```` HTML ````html ```` ### Констуркция Switch Case Pug поддерживает switch case, которая представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами. Pug ````pug - var friends = 10 case friends when 0 p you have no friends when 1 p you have a friend default p you have #{friends} friends ```` HTML ````html

you have 10 friends

```` ### Циклы Pug ````pug ul each val, index in ['zero', 'one', 'two'] li= index + ': ' + val ```` HTML ````html ```` *** Pug ````pug - var values = []; ul each val in values li= val else li There are no values ```` HTML ````html ```` *** Pug ````pug - var n = 0; ul while n < 4 li= n++ ```` HTML ````html ```` ### Вставка JavaScript кода Pug поддерживает вставку частей JavaScript кода в шаблоны. Не буфферизированный код начинается с символа `-` Pug ````pug - for (var x = 0; x < 3; x++) li item ```` HTML ````html
  • item
  • item
  • item
  • ```` *** Буфферизированный код начинается с символа `=` Pug ````pug p = 'This code is !' ```` HTML ````html

    This code is <escaped>!

    ```` ### Комментарии Существуют различные комментариев: те, которые будут отображаться после компиляции, и те, которые пропадут. Pug ````pug // just some paragraphs //- will not output within markup p foo p bar ```` HTML ````html

    foo

    bar

    ```` *** Pug ````pug body //- Comments for your template writers. Use as much text as you want. // Comments for your HTML readers. Use as much text as you want. ```` HTML ````html ```` ### Условия Pug ````pug - var user = { description: 'foo bar baz' } - var authorised = false #user if user.description h2.green Description p.description= user.description else if authorised h2.blue Description p.description. User has no description, why not add one... else h2.red Description p.description User has no description ```` HTML ````html

    Description

    foo bar baz

    ```` ### Тип документа Pug ````pug doctype html ```` HTML ````html ```` ### Инклюды (Includes) Pug имеет возможность вставки содержимого одного файла в другой файл Pug. Pug ````pug //- index.pug doctype html html head style include style.css body h1 My Site p Welcome to my super lame site. script include script.js ```` CSS ````css /* style.css */ h1 { color: red; } ```` JavaScript ````js // script.js console.log('You are awesome'); ```` HTML ````html

    My Site

    Welcome to my super lame site.

    ```` ### Наследование шаблонов Pug поддерживает наследование шаблонов. Наследование шаблонов работает через ключевые слова `block` и `extend`. В шаблоне `block` - обычный блок Pug, который может заменить дочерний шаблон. Этот процесс является рекурсивным. Pug ````pug //- base.pug html head title My Site block scripts script(src='/jquery.js') body block content block foot #footer p some footer content //- home.pug extends base.pug - var title = 'Animals' - var pets = ['cat', 'dog'] block content h1= title // - or #{title} without = each petName in pets p= petName // -or #{petName} without = ```` HTML ````html My site

    Animals

    cat

    dog

    ```` ### Интерполяция переменных Pug предоставляет различные способы вывода переменных. Pug ````pug - var title = "On Dogs: Man's Best Friend"; - var author = "enlore"; - var theGreat = "escape!"; h1= title p Written with love by #{author} p This will be safe: !{theGreat} ```` HTML ````html

    On Dogs: Man's Best Friend

    Written with love by enlore

    This will be safe: escape!

    ```` ### Миксины Поддержка миксинов позволяет создавать переиспользуемые блоки. Pug ````pug //- Declaration mixin pet(name) li.pet= name //- use ul +pet('cat') +pet('dog') +pet('pig') ```` HTML ````html ```` *** Pug ````pug mixin article(title) .article .article-wrapper h1= title if block block else p No content provided +article('Hello world') +article('Hello world') p This is my p Amazing article ```` HTML ````html

    Hello world

    No content provided

    Hello world

    This is my

    Amazing article

    ```` *** Pug ````pug mixin link(href, name) //- attributes == {class: "btn"} a(class!=attributes.class href=href)= name +link('/foo', 'foo')(class="btn") ```` HTML ````html foo ```` ### Многострочный ассоциативный массив Pug ````pug - var priceItem = [ {include: filterInc, parameter : "Розовый фильтр"}, {include: smileInc, parameter : "Смайлики"}, {include: commentInc, parameter : "Комментарии"} ] ````