© Jörg Krause 2017

Jörg Krause, Programming Web Applications with Node, Express and Pug , 10.1007/978-1-4842-2511-0_7

7. Language Components of Pug

Jörg Krause

(1)Berlin, Germany

In the following, you find a systematic language overview. The entrance to the available online information can be found on [Github] ( https://github.com/Pugjs/Pug ).

Doctype

The typical HTML 5 Doctype is written as follows:

1   doctype html

The produced HTML then looks as follows:

1   <!DOCTYPE html>

Short Spellings

Because of the frequent use of Doctypes there are a few short spellings .

1   doctype html

The produced HTML then looks as follows:

1   <!DOCTYPE html>
1   doctype xml

The produced HTML then looks as follows:

1   <?xml version="1.0" encoding="utf-8" ?>

1   doctype transitional

The produced HTML then looks as follows:

1   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http
2   ://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


1   doctype strict

The produced HTML then looks as follows:

1   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www
2   .w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


1   doctype frameset

The produced HTML then looks as follows:

1   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://w
2   ww.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">


1   doctype 1.1

The produced HTML then looks as follows:

1   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org
2   /TR/xhtml11/DTD/xhtml11.dtd">


1   doctype basic

The produced HTML then looks as follows:

1   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.
2   w3.org/TR/xhtml-basic/xhtml-basic11.dtd">


1   doctype mobile

The produced HTML then looks as follows:

1   <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http:
2   //www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">

Own Doctypes

If deviating Doctypes are necessary, the following syntax can be used:

1   doctype html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"

The following HTML is provided by it:

1   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN">

Options

The Doctypes are not only a source of information for the browser. You should absolutely take the Pug version, because these also affect the HTML generator , for example, on handling closing tags.

Here is the direct call of the Renderers with the Doctype “XHTML”:

1   var pug = require('pug');
2
3   // Translate
4   var fn = pug.compile('img(src="foo.png")',
5                        { doctype: 'xml' });
6
7   // Rendering
8   var html = fn({});

The following HTML is provided by it:

1   <img src="foo.png"></img>

But if HTML is produced, the tag won’t be closed:

1   // Compilation            
2   var fn = pug.compile('img(src="foo.png")',
3                         { doctype: 'html' });
4
5   // Rendering
6   var html = fn({});

The following HTML is provided by it:

1   <img src="foo.png">

Attributes

Attributes look as in HTML; however, the arguments are JavaScript, so that you can simply work dynamically here.

A435076_1_En_7_Figa_HTML.jpg Server Side JavaScript

Note that JavaScript is implemented in arguments on the server and is sending static HTML from the view of the client.

1   a(href='google.com') Google
2   a(class='button', href='google.com') Google

Translated, this looks as follows:

1   <a href="google.com">Google</a><a href="google.com" class="button">G
2   oogle</a>

All usual JavaScript expressions function without problems. They are separated with “-”, so that Pug won’t interpret them as HTML:

1   - var authenticated = true          
2   body(class=authenticated ? 'auth' : 'anon')

Translated, this looks as follows:

1   <body class="auth"></body>

Several attributes can be divided for the improvement of readableness on several lines:

1   input(
2     type='checkbox'
3     name='agreement'
4     checked
5   )

Translated to HTML this looks as follows:

1   <input type="checkbox" name="agreement" checked="checked"/>

Not coded Attribute

According to standard all attributes are coded, i.e., special characters are replaced by appropriate entities (“<” with & gt; and “>” with & it; etc.). With the assignment characters “=” and “!=”, the behavior can be steered:

1   div(escaped="<code>")
2   div(unescaped!="<code>")

In HTML this looks as follows:

1   <div escaped="&lt;code&gt;"></div>
2   <div unescaped="<code>"></div>
A435076_1_En_7_Figb_HTML.jpg Caution!

It is dangerous with user inputs, which are passed on to sightings in order to turn the coding off. Users can otherwise transfer active code to the server:

Logical Attributes

Logical (boolean) attributes are represented in Pug as functions, which can process arguments. For its part, they can either be true or false. If no argument is indicated, the standard is true.

1   input(type='checkbox', checked)
2   input(type='checkbox', checked=true)
3   input(type='checkbox', checked=false)
4   input(type='checkbox', checked=true.toString())

Translated this looks as follows:

1   <input type="checkbox" checked="checked"/>
2   <input type="checkbox" checked="checked"/>
3   <input type="checkbox"/>
4   <input type="checkbox" checked="true"/>

If the Doctype of the document is HTML, the shortened attributes are used, as they understand all browsers:

1   doctype html
2   input(type='checkbox', checked)
3   input(type='checkbox', checked=true)
4   input(type='checkbox', checked=false)
5   input(type='checkbox', checked=true && 'checked')

Translated this looks as follows:

1   <!DOCTYPE html>
2   <input type="checkbox" checked>
3   <input type="checkbox" checked>
4   <input type="checkbox">
5   <input type="checkbox" checked="checked">

Style Attributes

The style attribute is somewhat more complex, because the parameters represent a style object. Contrary to the pure HTML version, which can be read only as character string. Pug is here indeed a JSON object.

1   a(style={color: 'red', background: 'green'})

In HTML this looks as follows:

1   <a style="color:red;background:green"></a>
A435076_1_En_7_Figc_HTML.jpg JSON

JSON stands for JavaScript Object Notation. This concerns a compact data format for humans and machine of simply readable text form for the purpose of data exchange between applications. Each valid JSON document should be valid JavaScript. One works on the server and on the client with JavaScript. It acts with JSON basically around the natural format for the data transfer and object definition.

& Attributes

This special form, known as “and attributes ,” is used in order to divide an object into attributes:

1   div#foo(data-bar="foo")&attributes({'data-foo': 'bar'})

In HTML this turns into:

1   <div id="foo" data-bar="foo" data-foo="bar"></div>

It must not be object literal. A variable which supplies an object itself is likewise suitable.

1   - var attributes = {'data-foo': 'bar'};
2   div#foo(data-bar="foo")&attributes(attributes)

Here, the same HTML starts to develop:

1   <div id="foo" data-bar="foo" data-foo="bar"></div>

A435076_1_En_7_Figd_HTML.jpg This function does not code HTML. If the data is from a user input, an explicit investigation on embedded codes is necessary. In addition, compare the handling with a mixin, which always takes over coding.

Handling CSS Classes

CSS classes are described by attributes or literals.

The Class Attribute

The class attribute can be used like every other attribute with a character string. Now it occurs frequently that several class names are set. But arrays are also permitted:

1   - var classes = ['btn', 'btn-default']
2   a(class=classes)
3   a.bing(class=classes class=['bing'])

As shown in line 3, the attribute can be repeated. Pug then combines the entries. Subsequently, it becomes the following in HTML:

1   <a class="btn btn-default"></a>
2   <a class="btn btn-default bing"></a>

If class names are set over conditions, usually a separate logic must be created. In Pug, Object Mapping is suitable for this:

1   - var curUrl = '/about'
2   a(class={active: curUrl === '/'} href='/') Home
3   a(class={active: curUrl === '/about'} href='/about') Über uns

This looks as follows in HTML:

1   <a href="/">Home</a>
2   <a href="/about" class="active">Über uns</a>

The Class Literal

The direct use of the literal one from CSSs is still simpler:

1   a.button

This looks as follows in HTML:

1   <a class="button"></a>

A feature with the literal ones is the “<div>” tag. This is the standard, if no element is indicated:

1   .content

In HTML it turns into the following:

1   <div class="content"></div>

ID Literal

IDs use the #idname syntax:

1   a#main-link

This looks as follows in HTML:

1   <a id="main-link"></a>

Since the “div” element is used very frequently, you can omit it:

1   #content

In HTML it turns into the following:

1   <div id="content"></div>

Instructions

Instructions bring interactive sections into the template. They resemble the possibilities of JavaScript, however before the script level is processed. HTML can be embedded directly.

Definition by Cases (case)

case is an instruction for process and corresponds to the switch in JavaScript. The case branches in JavaScript are written as when in Pug:

1   - var friends = 10
2   case friends
3     when 0
4       p You have no friends
5     when 1
6       p You have one friend
7     default
8       p You have #{friends} friends

In HTML it turns into the following:

1   <p>You have 10 friends</p>

Forwarding to the next Case

Just like in JavaScript, the instruction for the next branch falls through if no instruction follows:

1   - var friends = 0
2   case friends
3     when 0
4     when 1
5       p Almost no friends
6     default
7       p You have #{friends} friends

In HTML it turns into the following:

1   <p>Almost no friends</p>

Extension of Blocks

Instead of the spelling of several lines, short texts can be placed on the same line and are then limited on this line:

1   - var friends = 1
2   case friends
3     when 0: p You have no friends
4     when 1: p You have one friend
5     default: p You have #{friends} friends

The HTML then looks as follows:

1   <p>You have one friend</p>

Conditions (if)

Conditions are an elementary component in Pug. In relation to JavaScript, the spelling is slightly simplified—so you can omit the clips around the condition.

 1   - var user = { description: 'Example Text' }
 2   - var authorised = false
 3   #user
 4     if user.description
 5       h2 Description
 6       p.description= user.description
 7     else if authorised
 8       h2 Description
 9       p.description.
10         User has no description,
11         add one...
12     else
13       h1 Description
14       p.description User has no description

The input data then determines which HTML will develop:

1   <div id="user">
2      <h2>Description</h2>
3      <p class="description">Example Text</p>
4   </div>

The keyword unless remains for negated conditions:

1   unless user.isAnonymous
2     p You are logged on as #{user.name}

This is perfectly identical to the following expression:

1   if !user.isAnonymous
2     p You are logged on as #{user.name}

Iterations

With each and while, two possibilities are available to form loops.

each

The use of each is, to a large extent, intuitive:

1   ul
2     each val in [1, 2, 3, 4, 5]
3       li= val

The HTML is formed on basis of the array on the server:

1   <ul>
2     <li>1</li>
3     <li>2</li>
4     <li>3</li>
5     <li>4</li>
6     <li>5</li>
7   </ul>

With two parameters, access to the index and the running value exists:

1   ul
2     each val, index in ['zero', 'one', 'two']
3       li= index + ': ' + val

The HTML shows that the index is based on zero:

1   <ul>
2     <li>0: zero</li>
3     <li>1: one</li>
4     <li>2: two</li>
5   </ul>

If Hashes (object maps) are used, then index and value can be determined even more exactly:

1   ul
2     each val, index in {1:'one',2:'two',3:'three'}
3       li= index + ': ' + val

The HTML shows that the index of the source object is certain:

1   <ul>
2     <li>1: one</li>
3     <li>2: two</li>
4     <li>3: three</li>
5   </ul>

Instead of the direct information, each JavaScript expression can be naturally used, which produces or contains a suitable structure:

1   - var values = [];
2   ul
3      each val in values.length ? values : ['No Values']
4        li= val

Since the array in the example is empty, the following HTML is produced:

1   <ul>
2     <li>No Values</li>
3   </ul>
A435076_1_En_7_Fige_HTML.jpg Pseudonym

The keyword “for” can be used as alias for “each.”

while

A loop with while has a termination condition. The loop keeps going, as long as the expression shows true.

1   - var n = 0
2   ul
3     while n < 4
4       li= n++

The dynamically produced HTML now looks as follows:

1   <ul>
2      <li>0</li>
3      <li>1</li>
4      <li>2</li>
5      <li>3</li>
6   </ul>

JavaScript Code

With Pug, JavaScript fragments can be written directly into the page.

These parts are then implemented on the server page. Thereby, there are three kinds of code:

Unbuffered Codes

The results when processing are written immediately into the output.

Buffered Codes

The results when processing are written first into a buffer and at the end sent completely to the instruction.

Buffered and not coded Codes

The results when processing are first written into a buffer and sent in the end completely to the instruction. No encoding of the output takes place.

Unbuffered Codes

Unbuffered and also not coded looks as follows:

1   - for (var x = 0; x < 3; x++)
2     li item
A435076_1_En_7_Figf_HTML.jpgCaution!

As in the preceding examples, you should keep caution during the conversion of user inputs, in order to prevent that such construct code is transferred. The transferred JavaScript code would be implemented in the server page.

In the HTML the following develops from the last example:

1   <li>item</li>
2   <li>item</li>
3   <li>item</li>

This also functions with blocks (the “-” indication is alone and set off while the following text is compressed):

1   -
2     list = ["Uno", "Dos", "Tres",
3             "Cuatro", "Cinco", "Seis"]
4   each item in list
5     li= item

Also, this loop generates pure HTML:

1   <li>Uno</li>
2   <li>Dos</li>
3   <li>Tres</li>
4   <li>Cuatro</li>
5   <li>Cinco</li>
6   <li>Seis</li>

Buffered Code

The buffered part starts indications with a “=” and spends the result of calculation in JavaScript. Here is the coded variant. (You consider the indentation on line 2.):

1   p
2     = 'This Code is <coded>!'

In HTML, you see how the special characters were converted:

1   <p>Dieser Code ist &lt;kodiert&gt;!</p>

JavaScript expressions can also begin here:

1   p= 'This cvode is' + ' <coded>!'

The same result happens as in the previous example:

1   <p>This Code is &lt;coded&gt;!</p>

Buffered and not coded Codes

The encoding starts again with the “!=” operator. Note that this is not safe regarding data from user inputs.

1   p
2     != 'This code is <strong>not</strong> coded!'

The following HTML is provided by it:

1   <p>This code is <strong>not</strong> coded!
2   </p>

Also in this use JavaScript expressions can be used:

1   p!= 'This code is' + ' <strong>not</strong> coded!'

The following HTML is provided by it:

1   <p>This code is <strong>not</strong> coded!</p>

Comments

Comments are written just as in JavaScript and then converted into HTML comments, thus not removed completely:

1   // Some HTML:          
2   p foo
3   p bar

The following HTML is provided by it:

1   <!-- Some HTML: -->
2   <p>foo</p>
3   <p>bar</p>

If somebody puts a line behind the comment symbol, the comment is removed and is not repeated in the HTML:

1   //- That's not public          
2   p foo
3   p bar

The following HTML is provided by it:

1   <p>foo</p>
2   <p>bar</p>

Comment Blocks

If a comment shall extend over several lines, then the comment symbol is placed alone on a line:

1   body
2     //
3       As many text
4       as you like

The following HTML is provided by it:

1   <body>
2     <!--
3       As many text
4       as you like
5    -->
6   </body>

Caused Comments

Internet Explorer can use sections conditionally, in order to write downwardly compatible HTML code. However, Pug has no special syntax. But since every not far recognized text is invariably spent, lines that begin with “<” indications will be transported directly into the HTML.

1   <!--[if IE 8]>
2   <html lang="en" class="lt-ie9">
3   <![endif]-->
4   <!--[if gt IE 8]><!-->
5   <html lang="en">
6   <!--<![endif]-->

Inherit from Templates

For inheriting templates the keyword “extends” is used. Thus, ranges of the layout page can be overwritten purposefully. First the layout page:

File: layout.pug

1   doctype html
2   html
3     head
4       block title
5         title Default title
6     body
7       block content

The actual page uses (inherits) this layout page. The range “block” (and therin the range “title”) is overwritten. The information is voluntary and, if they are missing, contents of the layout page would be shown.

File: index.pug

1   extends layout
2
3   block title
4     title My Articles
5
6   block content
7     h1 Here is some content

The final HTML now looks as follows:

1   <!doctype html>
2   <html>
3     <head>
4       <title>My Articles</title>
5     </head>
6     <body>
7       <h1>Here is some content</h1>
8     </body>
9   </html>
A435076_1_En_7_Fig1_HTML.jpg
Figure 7-1. Output of the Master Page
A435076_1_En_7_Figg_HTML.jpg More Complex Layouts

The inheritance of the layout page can go over several stages, i.e., in a layout page a further can be called. Thus more complex interlocked layouts can be sketched.

Detail for inherting Templates

The simple inheriting of templates can be extended if you specify “block” ranges, which can be overwritten purposefully. A “block” is thereby pug code, which can be replaced. The procedure is recursive.

If the placeholder is equipped with contents, this functions as standard. Regard the following layout page:

File:layout.pug

 1   html
 2     head
 3       title My Site - #{title}
 4       block scripts
 5         script(src='/jquery.js')
 6     body
 7       block content
 8       block foot
 9         #footer
10           p Content of Footer

This is now used by means of extends. The page index.pug in the following example overwrites thereby the blocks scripts and content. However, the block foot remains unchanged and is taken over by the layout page.

File: index.pug

 1   extends layout
 2
 3   block scripts
 4     script(src='scripts/jquery.js')
 5     script(src='scripts/data.js')
 6
 7   block content
 8     h1= title
 9     each pet in pets
10       include pet

In a block further blocks can be defined, which are again overwritten with further derivatives of interlocked layout pages. The further layout page sub-layout.pug is defined as follows:

File: sub-layout.pug

1   extends layout
2
3   block content
4     .sidebar
5       block sidebar
6         p nothing
7     .primary
8       block primary
9         p nothing

The page page-b.pugnow uses this derived layout page:

File: page-b.pug

1   extends sub-layout
2
3   block content
4     .sidebar
5       block sidebar
6         p nothing
7     .primary
8       block primary
9         p nothing

The blocks sidebar and primary are overwritten here.

Prepend and append Content Blocks

Apart from blank, replacing contents can also be placed in front (prepend) or supplement (append). With the definition, nothing changes at first:

1   html
2     head
3       block head
4         script(src='/vendor/jquery.js')
5         script(src='/vendor/bootstrap.js')
6     body
7       block content

Further scripts can now be supplemented as follows:

1   extends layout
2
3   block append head
4      script(src='/scripts/data.js')

The keyword “block” is optional with the use of “prepend” and “append”:

1   extends layout
2
3   append head
4     script(src='/scripts/data.js')
A435076_1_En_7_Figh_HTML.jpg File Extension

In this example the file extension .pug was omitted.This is optional, if the standard .pug is used.

Filter

Filters serve to use another language within the source text. Typical examples are Markdown and CoffeeScript.

1   :markdown
2     # Markdown
3
4     I often like including markdown documents.
5
6   script
7     :coffee-script
8       console.log 'This is coffee script'

The language block is properly introduced and accordingly interpreted with the “:” indication. The preceding example in HTML looks as follows:

1   <h1>Markdown</h1>
2   <p>I often like including markdown documents.</p>
3   <script>console.log('This is coffee script')</script>
A435076_1_En_7_Figi_HTML.jpg Time of Action

Filters are implemented by the translation of the page. Within the filter, therefore, no dynamic expressions can stand. The execution for it is very fast.

Partial Pages

Complex pages can be divided—into partial pages, to be exact. Intergration takes place with the keyword includes and the information of the file name, if necessary, with the relative path.

File: index.pug

1   doctype html
2   html
3     include ./parts/head.pug
4     body
5       h1 My Site
6       p Welcome to my super lame site.
7       include ./includes/foot.pug

File: parts/head.pug

1   head
2     title Meine Seite
3     script(src='/javascripts/jquery.js')
4     script(src='/javascripts/app.js')

File: parts/foot.pug

1   #footer
2     p Copyright (c) foobar

From this the following HTML develops:

 1   <!doctype html>
 2   <html>
 3     <head>
 4       <title>My Site</title>
 5       <script src='/javascripts/jquery.js'></script>
 6       <script src='/javascripts/app.js'></script>
 7     </head>
 8     <body>
 9       <h1>My Site</h1>
10       <p>Welcome to my super site.</p>
11       <div id="footer">
12         <p>Copyright (c) JoergIsGeek</p>
13       </div>
14     </body>
15   </html>

Merge Text

Partial pages do not only have to be Pug. Simple text can also be used. Pug recognizes this automatically.

index.pug

 1   doctype html
 2   html
 3     head
 4       style
 5         include style.css
 6     body
 7       h1 My Site
 8       p Welcome to my super site.
 9       script
10         include script.js

style.css

1   /* style.css */            
2   h1 { color: red; }

script.js

1   // script.js            
2   console.log('You are awesome');

From this the following HTML develops:

 1   <!doctype html>
 2   <html>
 3     <head>
 4       <style>
 5         /* style.css */
 6         h1 { color: red; }
 7       </style>
 8     </head>
 9     <body>
10       <h1>My Site</h1>
11         <p>Welcome to my super site.</p>
12         <script>
13           // script.js
14           console.log('You are awesome');
15         </script>
16       </body>
17   </html>

Combination of Filters and Partial Pages

With the combination of filters and partial pages, other pages are merged which contain contents in other languages.

File: index.pug

1   doctype html
2   html
3     head
4       title An Article
5     body
6       include:markdown article.md

The enclosed page is here interpreted as Markdown:

File: article.md

1   # Heading in Markdown
2
3   This article has been created in Markdown

From this the following HTML develops:

 1   <!doctype html>
 2   <html>
 3     <head>
 4       <title>An Article</title>
 5     </head>
 6     <body>
 7       <h1>Heading in Markdown</h1>
 8       <p>This article has been created in Markdown.</p>
 9     </body>
10   </html>

The combination with Markdown is especially interesting, because already existing contents can be invariably taken over.

Interpolations

Interpolations replace variables in character sequences. Nearly every programming language probably knows comparable techniques. Pug knows the following operators:

  • coded character string interpolation

  • not coded string interpolation

  • Tag Interpolation

Coded Character String Interpolation

In the following template some variables are defined and then used in expressions, without accessing JavaScript syntax again:

1   - var title = "Introduction to Node.js";
2   - var author = "Joerg";
3   - var version = "<span>4.1</span>";
4
5   h1= title
6   p Collected by #{author}
7   p #{version}

The following HTML shows the result of the interpolation:

1   <h1>Introduction to Node.js</h1>
2   <p>Collected by Joerg</p>
3   <p>For Version: &lt;span&gt;4.1!&lt;/span&gt;</p>

The code between “#{” and “}” is evaluated, coded and sent as buffered result to the output. The expression can be again JavaScript, so that even more complex expressions can develop.

1   - var msg = "really cool";
2   p Dies ist #{msg.toUpperCase()}

In this case, rather cool HTML develops from it:

1   <p>This is REALLY COOL</p>

Not Coded String Interpolation

If security is not necessary or desired in HTML, the not coded variant would work again:

1   - var riskyQuote = "<em>Node requires pug.</em>";
2   .quote
3   p Joerg: !{riskyQuote}

The HTML is invariably spent:

1   <div class="quote">
2      <p>Joerg: <em>Node requires pug.</em></p>
3   </div>

Tag Interpolation

Interpolations can also directly be used as tags. For this “#[]” is used.

1   p.
2     If you get the sources on #[a(target="_blank", href="https://githu
3   b.com/pugjs/pug/blob/master/docs/views/reference/interpolation.pug")
4    GitHub],
5      you'll see, at how many places we use Interpolation.

From this quite compact HTML develops:

1   <p>If you get the sources on <a target="_blank" href="https://githu
2   b.com/pugjs/pug/blob/master/docs/views/reference/interpolation.pug">
3    GitHub</a>,
4     you'll see, at how many places we use Interpolation.
5   </p>

The Renderer uses its buffer internally for the tray and for passing on, so that this is better than directly merging HTML.

Mixins (Functions)

Mixins produce re-usable blocks made out of Pug code. Thus, endless repetitions of the same HTML components can be avoided. Particularly in connection with Bootstrap, more complex constructs can be prepared and start at any time.

A Mixin (read: Function) is defined as follows:

1   mixin list
2     ul
3       li foo
4       li bar
5       li baz

The use is based on a special operator:

1   +list
2   +list

The use is introduced with the “+” indication. In the HTML, nothing more about it can be found:

 1   <ul>
 2     <li>foo</li>
 3     <li>bar</li>
 4     <li>baz</li>
 5   </ul>
 6   <ul>
 7     <li>foo</li>
 8     <li>bar</li>
 9     <li>baz</li>
10   </ul>

Mixins are JavaScript functions and can be provided with parameters:

1   mixin pet(name)
2     li.pet= name
3   ul
4     +pet('Cat')
5     +pet('Dog')
6     +pet('Bird')

The following HTML develops from it:

1   <ul>
2     <li class="pet">Cat</li>
3     <li class="pet">Dog</li>
4     <li class="pet">Bird</li>
5   </ul>

Mixin Blocks

Mixin can take up a block with a Pug code and thereby win more dynamics:

 1   mixin article(title)
 2     .article
 3       .article-wrapper
 4         h1= title
 5         if block
 6           block
 7         else
 8           p No Content
 9
10   +article('Hello pug')
11
12   +article('Hello pug')
13     p This is an
14     p article about Node.js

The following HTML develops from it:

 1   <div class="article">
 2     <div class="article-wrapper">
 3       <h1>Hello pug</h1>
 4       <p>No content</p>
 5     </div>
 6   </div>
 7   <div class="article">
 8     <div class="article-wrapper">
 9       <h1>Hello pug</h1>
10       <p>This is an</p>
11       <p>article about Node.js</p>
12     </div>
13   </div>

Mixin Attributes

Similar to JavaScript functions, Mixins parameters can take up objects over an implicit “attribute”:

1   mixin link(href, name)
2     //- attributes == {class: "btn"}
3     a(class!=attributes.class, href=href)= name
4
5   +link('/foo', 'foo')(class="btn")

The following HTML develops from it:

1   <a href="/foo" class="btn">foo</a>

A435076_1_En_7_Figj_HTML.jpg The values are coded automatically. If that is not desired, “!=” shall be used. A combination with the “&attributes” is just as possible.

1   mixin link(href, name)
2     a(href=href)&attributes(attributes)= name
3
4   +link('/foo', 'foo')(class="btn")

The following HTML develops from it:

1   <a href="/foo" class="btn">foo</a>

Further Arguments

If the number of arguments is only partly variable, a definition of the kind “the whole rest” can be constructed:

1   mixin list(id, ...items)
2     ul(id=id)
3       each item in items
4         li= item
5
6   +list('my-list', 1, 2, 3, 4)

The following HTML develops from it:

1   <ul id="my-list">
2     <li>1</li>
3     <li>2</li>
4     <li>3</li>
5     <li>4</li>
6   </ul>

Handling Text

Simple text is not interpreted and is not invariably spent, even if it contains control characters.

Connect Text

The “|” operator (“pipe”) continues preceding lines simply with text.

1   | Simple text can contain <strong>html</strong>
2   p
3      | But it must be alone on the line

The text arrives invariably in the HTML page:

1   Simple text can contain <strong>html</strong>
2   <p>But it must be alone on the line</p>

Inline in Tag

Tags in Tags are at the agenda in HTML. Because in nearly each block element are various inline elements to find (<span> in <div>). Text after an element is invariably taken over and can contain HTML. That is often simpler to define than the complete hierarchy:

1   p Simple text can contain <strong>HTML</strong>

The HTML arrives invariably in the page:

1   <p>Simple text can contain <strong>HTML</strong> </p>

Block in Tag

Often large blocks with text are needed. Scripts or longer style definitions are good examples of it. Here interactivity is required rarely. In order to introduce such a block, the element instruction point becomes a “.” placed behind itself:

1   script.
2     if (usingpug)
3       console.log('you are awesome')
4     else
5       console.log('use pug')

The contents arrive invariably in the page:

1   <script>
2     if (usingpug)
3       console.log('you are awesome')
4     else
5       console.log('use pug')
6   </script>

Handling Tags

Tags are only described by their name, without the Markup clips.

The hierarchy is specified by the indentation (two blanks).

1   ul
2     li Item A
3     li Item B
4     li Item C

From this example valid HTML develops:

1   <ul>
2     <li>Item A</li>
3     <li>Item B</li>
4     <li>Item C</li>
5   </ul>

If the Doctype requires this, self-closing elements will be produced automatically. For the element “img”, this looks as follows:

1   img

Here valid HTML develops with a closing tag:

1   <img/>

Extension of Blocks

Interlocked blocks can be defined in a line, as long as no contents follow. This takes place via “:” operator. This takes place with frequent typical combinations, for example with hyperlinks:

1   a: img

From this example valid HTML develops as follows:

1   <a><img/></a>

Self-Closing Tags

Some tags, such as img, meta, and link never contain contents.

They are therefore self-closing, except with the XML Doctype. If this is to be shown independently of the Doctype, this can take place with concluding “/” indications.

1   meta/
2   link(rel='stylesheet')/

From this example the following HTML develops:

1   <meta/>
2   <link rel="stylesheet"/>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.237.24