How To Template With Pug
Every bit a programmer, I appreciate how Athwart apps are structured and the many options the Angular CLI makes available to configure them. Components provide an astonishing means to structure views, facilitate code reusability, interpolation, data binding, and other business logic for views.
Angular CLI supports multiple built-in CSS preprocessor options for component styling similar Sass/SCSS, LESS, and Stylus. Even so, when it comes to templates, only two options are bachelor: HTML and SVG. This is in spite of many more efficient options such as Pug, Slim, HAML amid others being in existence.
In this article, I'll cover how yous — every bit an Athwart developer — tin can utilise Pug to write amend templates more efficiently. You'll larn how to install Pug in your Angular apps and transition existing apps that utilize HTML to utilize Pug.
Managing Image Breakpoints
A congenital-in Angular feature called BreakPoint Observer gives us a powerful interface for dealing with responsive images. Read more about a service that allows u.s.a. to serve, transform and manage images in the cloud. Read a related article →
More subsequently jump! Proceed reading beneath ↓
Pug (formerly known equally Jade) is a template engine. This means information technology's a tool that generates documents from templates that integrate some specified data. In this case, Pug is used to write templates that are compiled into functions that take in data and render HTML documents.
In addition to providing a more streamlined fashion to write templates, information technology offers a number of valuable features that get across but template writing like mixins that facilitate code reusability, enable embedding of JavaScript code, provide iterators, conditionals, and so on.
Although HTML is universally used by many and works fairly in templates, it is not DRY and tin can get pretty difficult to read, write, and maintain peculiarly with larger component templates. That'southward where Pug comes in. With Pug, your templates get simpler to write and read and you can extend the functionality of your template as an added bonus. In the remainder of this article, I'll walk you through how to employ Pug in your Angular component templates.
Why Yous Should Use Pug
HTML is fundamentally repetitive. For most elements you have to take an opening and closing tag which is not DRY. Not just do you take to write more with HTML, but you lot also have to read more. With Pug, there are no opening and endmost angle brackets and no closing tags. Y'all are therefore writing and reading a lot less lawmaking.
For case, here'southward an HTML tabular array:
<table> <thead> <tr> <thursday>Country</th> <thursday>Capital letter</th> <thursday>Population</th> <th>Currency</th> </tr> </thead> <tbody> <tr> <td>Canada</td> <td>Ottawa</td> <td>37.59 million</td> <td>Canadian Dollar</td> </tr> <tr> <td>S Africa</td> <td>Cape Town, Pretoria, Bloemfontein</td> <td>57.78 one thousand thousand</td> <td>Due south African Rand</td> </tr> <tr> <td>United Kingdom</td> <td>London</td> <td>66.65 one thousand thousand</td> <td>Pound Sterling</td> </tr> </tbody> </tabular array>
This is how that same table looks like in Pug:
table thead tr th Land thursday Uppercase(southward) th Population th Currency tbody tr td Canada td Ottawa td 37.59 million td Canadian Dollar tr td South Africa td Cape Town, Pretoria, Bloemfontein td 57.78 meg td South African Rand tr td United Kingdom td London td 66.65 meg td Pound Sterling
Comparing the two versions of the table, Pug looks a lot cleaner than HTML and has better code readability. Although negligible in this small case, you write seven fewer lines in the Pug tabular array than in the HTML tabular array. As y'all create more templates over time for a project, y'all cease up cumulatively writing less code with Pug.
Beyond the functionality provided past the Angular template language, Pug extends what yous can achieve in your templates. With features (such as mixins, text and aspect interpolation, conditionals, iterators, so on), you tin can utilize Pug to solve problems more simply in contrast to writing whole separate components or import dependencies and ready directives to fulfill a requirement.
Some Features Of Pug
Pug offers a broad range of features but what features yous can use depends on how you lot integrate Pug into your project. Here are a few features you lot might find useful.
- Calculation external Pug files to a template using
include
.Let'south say, for example, that y'all'd like to have a more than succinct template just do not feel the demand to create additional components. You can take out sections from a template and put them in fractional templates so include them dorsum into the original template.
For case, in this habitation page component, the 'About' and 'Services' department are in external files and are included in the home page component.
//- domicile.component.pug h1 Leone and Sons h2 Photography Studio include partials/about.partial.pug include partials/services.partial.pug
//- about.partial.pug h2 Near our business p Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
//- services.partial.pug h2 Services nosotros offer P Our services include: ul li Headshots li Corporate Result Photography
- Reusing lawmaking blocks using mixins.
For case, let'due south say you wanted to reuse a code block to create some buttons. Y'all'd reuse that cake of code using a mixin.
mixin bill of fare-button(text, action) button.btn.btn-sm.1000-1('(click)'=action)&attributes(attributes)= text +menu-button('Relieve', 'saveItem()')(form="btn-outline-success") +card-button('Update', 'updateItem()')(form="btn-outline-principal") +menu-button('Delete', 'deleteItem()')(form="btn-outline-danger")
- Conditionals brand information technology easy to display code blocks and comments based on whether a condition is met or not.
- var 24-hour interval = (new Engagement()).getDay() if day == 0 p Nosotros're closed on Sundays else if day == 6 p We're open up from 9AM to 1PM else p We're open up from 9AM to 5PM
- Iterators such as
each
andwhile
provide iteration functionality.
ul each item in ['Eggs', 'Milk', 'Cheese'] li= item ul while n < v li= n++ + ' bottles of milk on the wall'
- Inline JavaScript tin can be written in Pug templates equally demonstrated in the examples above.
- Interpolation is possible and extends to tags and attributes.
- var name = 'Charles' p Hi! I'm #{proper noun}. p I'm a #[stiff web developer]. a(href='https://about.me/${proper name}') Get to Know Me
- Filters enable the use of other languages in Pug templates.
For example, you tin can use Markdown in your Pug templates after installing a JSTransformer Markdown module.
:markdown-information technology # Charles the Web Developer ![Image of Charles](https://charles.com/contour.png) ## About Charles has been a web programmer for xx years at **Charles and Co Consulting.**
These are just a few features offered past Pug. You can find a more expansive listing of features in Pug'southward documentation.
How To Utilise Pug In An Angular App
For both new and pre-existing apps using Angular CLI 6 and above, you will need to install ng-cli-pug-loader
. Information technology's an Angular CLI loader for Pug templates.
For New Components And Projects
- Install
ng-cli-pug-loader
.
ng add ng-cli-pug-loader
- Generate your component according to your preferences.
For case, let's say we're generating a home page component:
ng g c home --style css -m app
- Change the HTML file extension,
.html
to a Pug extension,.pug
. Since the initial generated file contains HTML, you may choose to delete its contents and start anew with Pug instead. However, HTML can still office in Pug templates then you tin can leave information technology as is. - Change the extension of the template to
.pug
in the component decorator.
@Component({ selector: 'app-component', templateUrl: './dwelling.component.pug', styles: ['./home.component.css'] })
For Existing Components And Projects
- Install
ng-cli-pug-loader
.
ng add ng-cli-pug-loader
- Install the html2pug CLI tool. This tool will aid you convert your HTML templates to Pug.
npm install -thousand html2pug
- To convert a HTML file to Pug, run:
html2pug -f -c < [HTML file path] > [Pug file path]
-f
to signal tohtml2pug
that it should not wrap the templates it generates inhtml
andbody
tags. The-c
flag letshtml2pug
know that attributes of elements should exist separated with commas during conversion. I volition cover why this is important below. - Alter the extension of the template to
.pug
in the component decorator as described in the For New Components and Projects section. - Run the server to check that in that location are no problems with how the Pug template is rendered.
If there are problems, use the HTML template as a reference to figure out what could take caused the problem. This could sometimes be an indenting consequence or an unquoted aspect, although rare. Once you lot are satisfied with how the Pug template is rendered, delete the HTML file.
Things To Consider When Migrating From HTML To Pug Templates
You won't be able to utilise inline Pug templates with ng-cli-pug-loader
. This only renders Pug files and does not return inline templates defined in component decorators. So all existing templates need to be external files. If you accept any inline HTML templates, create external HTML files for them and convert them to Pug using html2pug
.
Once converted, y'all may demand to fix templates that use bounden and attribute directives. ng-cli-pug-loader
requires that bound attribute names in Angular exist enclosed in unmarried or double quotes or separated by commas. The easiest fashion to get about this would be to use the -c
flag with html2pug
. However, this but fixes the issues with elements that have multiple attributes. For elements with unmarried attributes just apply quotes.
A lot of the setup described here can be automated using a task runner or a script or a custom Angular schematic for large scale conversions if you choose to create 1. If you take a few templates and would like to do an incremental conversion, it would be better to just convert one file at a fourth dimension.
Angular Template Language Syntax In Pug Templates
For the most part, Angular template language syntax remains unchanged in a Pug template, however, when information technology comes to binding and some directives (as described to a higher place), yous need to utilise quotes and commas since ()
, []
, and [()]
interfere with the compilation of Pug templates. Here are a few examples:
//- [src], an aspect binding and [style.border], a manner binding are separated using a comma. Utilize this approach when you have multiple attributes for the element, where one or more is using bounden. img([src]='itemImageUrl', [style.edge]='imageBorder') //- (click), an issue binding needs to be enclosed in either single or double quotes. Use this arroyo for elements with simply ane attribute. button('(click)'='onSave($issue)') Save
Attribute directives similar ngClass
, ngStyle
, and ngModel
must exist put in quotes. Structural directives like *ngIf
, *ngFor
, *ngSwitchCase
, and *ngSwitchDefault
too need to be put in quotes or used with commas. Template reference variables ( e.one thousand. #var
) exercise not interfere with Pug template compilation and hence practise not need quotes or commas. Template expressions surrounded in {{ }}
remain unaffected.
Drawbacks And Trade-offs Of Using Pug In Athwart Templates
Fifty-fifty though Pug is convenient and improves workflows, there are some drawbacks to using it and some merchandise-offs that need to be considered when using ng-cli-pug-loader
.
Files cannot be included in templates using include
unless they stop in .partial.pug
or .include.pug
or are called mixins.pug
. In addition to this, template inheritance does not piece of work with ng-cli-pug-loader
and as a result, using blocks, prepending, and appending Pug code is non possible despite this being a useful Pug feature.
Pug files take to be created manually every bit Athwart CLI simply generates components with HTML templates. Yous will need to delete the generated HTML file and create a Pug file or only change the HTML file extension, then alter the templateUrl
in the component decorator. Although this tin exist automated using a script, a schematic, or a Chore Runner, you lot take to implement the solution.
In larger pre-existing Angular projects, switching from HTML templates to Pug ones involves a lot of work and complexity in some cases. Making the switch will pb to a lot of breaking code that needs to be fixed file by file or automatically using a custom tool. Bindings and some Angular directives in elements demand to exist quoted or separated with commas.
Developers unfamiliar with Pug take to learn the syntax showtime before incorporating it into a project. Pug is not only HTML without angle brackets and closing tags and involves a learning curve.
When writing Pug and using its features in Athwart templates ng-cli-pug-loader
does not give Pug templates admission to the component's properties. Every bit a upshot, these backdrop cannot be used as variables, in conditionals, in iterators, and in inline code. Angular directives and template expressions also do not have access to Pug variables. For example, with Pug variables:
//- app.component.pug - var shoppingList = ['Eggs', 'Milk', 'Flour'] //- will work ul each item in shoppingList li= item //- will not work because shoppingList is a Pug variable ul li(*ngFor="allow particular of shoppingList") {{item}}
Hither's an instance with a property of a component:
//- src/app/app.component.ts export class AppComponent{ shoppingList = ['Eggs', 'Milk', 'Flour']; }
//- app.component.pug //- will non work because shoppingList is a component holding and non a Pug variable ul each item in shoppingList li= item //- will work because shoppingList is a property of the component ul li(*ngFor="let item of shoppingList") {{detail}}
Lastly, index.html
cannot exist a Pug template. ng-cli-pug-loader
does non support this.
Conclusion
Pug can be an astonishing resource to use in Angular apps but it does crave some investment to learn and integrate into a new or pre-existing project. If yous're up for the claiming, you can take a look at Pug'south documentation to acquire more about its syntax and add it to your projects. Although ng-cli-pug-loader
is a great tool, it can be lacking in some areas. To tailor how Pug volition work in your project consider creating an Angular schematic that volition run across your project'southward requirements.
(ra, yk, il)
How To Template With Pug,
Source: https://www.smashingmagazine.com/2020/05/angular-templates-pug/
Posted by: bishoplonswellot.blogspot.com
0 Response to "How To Template With Pug"
Post a Comment