(templates)= # Templates We use [PyPugJS](https://github.com/kakulukia/pypugjs) (formerly *Pyjade*) as a Jinja extension. Templates with the extension `.j2.jade` or `.j2.pug` are passed to PyPugJS and converted to a Jinja template. Our templates mostly support the syntax of [Pug](https://pugjs.org/api/getting-started.html) which was called *Jade* before. Instead of Javascript, pieces of code in templates are interpreted as Jinja code. Keep that in mind when reading the language reference for Pug. As a basic rule, keep complicated logic away from templates and use Python code from the cell associated with a template. Reading existing templates and following their style is a good idea. ## HTML Tags and Attributes By default, text at the start of a line (or after only white space) represents an HTML tag. Indented tags are nested, creating the tree structure of HTML. ```pug ul li Item A li Item B li Item C ``` Tag attributes look similar to HTML, with optional commas between them. Simple values are strings with quotes: ```pug a(href='//example.com', target='_blank') Example ``` ### Class and ID Literal In addition to using the class attribute like in HTML, classes can be added to tags with the `.classname` syntax: ```pug a.button.button-primary ``` ```html ``` For divs, you can skip writing `div` and just use a class literal: ```pug .content ``` ```html
``` ID literals follow the same rules start with a `#`. ### Values from Expressions Attribute values support Jinja expressions: ```pug a.link(href=example_url, class=("extra" if options.extra else "")) Example ``` Adds "extra" to class attribute only if options.extra is true: ```html Example ``` ### Boolean Attributes ```pug input(type='checkbox' checked) [x] | input(type='checkbox' checked=true) [x] | input(type='checkbox' checked=false) [] ``` ### Differences to Pug - Jinja expressions instead of Javascript - no multiline attributes - no special handling of class and style attributes - no support for `&attributes` syntax ## Code ### Buffered (With Output) `=` is used to produce output from a Jinja expression. Pug calls this *buffered code*. This works like `{{ }}` in Jinja. For security, output is automatically escaped by Jinja. ```pug p = 'This code isSome Text More Text
``` ### Mixing Code with Text Let's say we want to output two values separated by a space: ```pug p = first_part | = second_part ``` ## Iteration Use for to iterate over a sequence: ```pug ul for item in items = li.list-item= item.text ``` ## Comments ```pug // comment which is rendered to a HTML comment //- comment which is just for the template, not rendered to HTML ``` ## Code Style - Always use 2 spaces for indentation. Do not mix! - Line length should not exceed 120, but sometimes it's necessary to write longer lines. - Avoid putting `= output` directly after a HTML tag, especially when it has multiple attributes. Put it on a indented line instead.