Html helper
Every web application generates lots of HTML markup. If the markup is static, it can be done efficiently by mixing EJS and HTML in a single file, but when it is generated dynamically it starts to get tricky to handle it without extra help. Pwoli provides such help in the form of an Html helper, which provides a set of static methods for handling commonly used HTML tags, their options, and their content.
Note: If your markup is nearly static, it’s better to use HTML directly. There’s no need to wrap absolutely everything in Html helper calls.
Basics
Since building dynamic HTML by string concatenation can get messy very fast, Pwoli provides a set of methods to manipulate tag options and build tags based on these options.
Generating Tags
The code for generating a tag looks like the following:
<%- Html.tag('p', Html.encode(user.name), {class: 'username'}) %>
The first argument is the tag name. The second one is the content to be enclosed between the start and end tags.
Note that we are using Html.encode
— that’s because the content isn’t encoded automatically to allow using HTML when needed.
The third one is an array of HTML options, or in other words, tag attributes.
In this array the key is the name of the attribute (such as class
, href
or target
), and the value is its value.
The code above will generate the following HTML:
<p class="username">codespede</p>
In case you need just an opening or closing tag, you can use the Html.beginTag()
and Html.endTag()
methods.
Options are used in many methods of the Html helper and various widgets. In all these cases there is some extra handling to know about:
- If a value is
null
, the corresponding attribute will not be rendered. - Attributes whose values are of boolean type will be treated as boolean attributes.
-
The values of attributes will be HTML-encoded using [[Html.encode Html.encode]]. -
If the value of an attribute is an array, it will be handled as follows:
- If the attribute is a data attribute as listed in [[Html.dataAttributes]], such as
data
orng
, a list of attributes will be rendered, one for each element in the value array. For example,{data: {id: 1, name: 'pwoli'}}
generatesdata.id="1" data.name="pwoli"
; and{data: {params: {id: 1, name: 'pwoli'}, status: 'ok'}
generatesdata.params={"id":1,"name":"pwoli"} data.status="ok"
. Note that in the latter example JSON format is used to render a sub-array. - If the attribute is NOT a data attribute, the value will be JSON-encoded. For example,
{params: {id: 1, 'name: 'pwoli'}
generatesparams={"id":1,"name":"pwoli"}
.
- If the attribute is a data attribute as listed in [[Html.dataAttributes]], such as
Forming CSS Classes and Styles
When building options for HTML tags we often start with defaults which we need to modify. In order to add or remove a CSS class you can use the following:
let let options = {class: 'btn btn-default'};
if (type === 'success') {
Html.removeCssClass(options, 'btn-default');
Html.addCssClass(options, 'btn-success');
}
console.log(Html.tag('div', 'Pwede na', options));
// if the value of type is 'success' it will render
// <div class="btn btn-success">Pwede na</div>
You may specify multiple CSS classes using the array style as well:
let let options = {class: ['btn', 'btn-default']};
console.log(Html.tag('div', 'Save', options));
// renders '<div class="btn btn-default">Save</div>'
You may also use the array style when adding or removing classes:
let let options = {class: 'btn'};
if (type === 'success') {
Html.addCssClass(options, ['btn-success', 'btn-lg']);
}
console.log(Html.tag('div', 'Save', options));
// renders '<div class="btn btn-success btn-lg">Save</div>'
Html.addCssClass()
prevents duplication, so you don’t need to worry about the same class appearing twice:
let options = {class: 'btn btn-default'};
Html.addCssClass(options, 'btn-default'); // class 'btn-default' is already present
console.log(Html.tag('div', 'Save', options));
// renders '<div class="btn btn-default">Save</div>'
If the CSS class option is specified using the array style, you may use a named key to mark the logical purpose of the class.
In this case, a class with the same key in the array style will be ignored in Html.addCssClass()
:
let options = {
class: [
'btn',
{ theme: 'btn-default' },
]
};
Html.addCssClass(options, {theme: 'btn-success'}); // 'theme' key is already taken
console.log(Html.tag('div', 'Save', options));
// renders '<div class="btn btn-default">Save</div>'
CSS styles can be set up in similar way using the style
attribute:
let options = {style: {width: '100px', height: '100px'}};
// gives style="width: 100px; height: 200px; position: absolute;"
Html.addCssStyle(options, height: 200px; position: 'absolute');
// gives style="position: absolute;"
Html.removeCssStyle(options, ['width', 'height']);
When using [[Html.addCssStyle|addCssStyle]], you can specify either an array of key-value pairs,
corresponding to CSS property names and values, or a string such as width: 100px; height: 200px;
. These formats
can be converted from one to the other using [[Html.cssStyleFromArray|cssStyleFromArray]] and
[[Html.cssStyleToArray|cssStyleToArray]]. The [[Html.removeCssStyle|removeCssStyle]]
method accepts an array of properties to remove. If it’s a single property, it can be specified as a string.
Encoding and Decoding Content
In order for content to be displayed properly and securely in HTML, special characters in the content should be encoded. For this, Pwoli provides two compact and simple-to-use methods:
let userName = Html.encode(user.name);
console.log(userName);
let decodedUserName = Html.decode(userName);
Forms
Dealing with form markup is quite repetitive and error prone. Because of that, there is a group of methods to help dealing with them.
Note: consider using [[ActiveForm ActiveForm]] in case you’re dealing with models and need validation.
Creating Forms
Forms can be opened with [[Html.beginForm | beginForm]] method like the following: |
<%- Html.beginForm(['order/update', {id: id}, 'post', {enctype: 'multipart/form-data'}]) %>
The first argument is the URL the form will be submitted to. It can be specified in the form of a Pwoli route.
The second one is the method to use. post
is the default. The third one is an array of options
for the form tag. In this case we’re changing the encoding of the form data in the POST request to multipart/form-data
,
which is required in order to upload files.
Closing the form tag is simple:
<%- Html.endForm() %>
Buttons
In order to generate buttons, you can use the following code:
<%- Html.button('Press me!', {class: 'teaser'}) %>
<%- Html.submitButton('Submit', {class: 'submit'}) %>
<%- Html.resetButton('Reset', {class: 'reset'}) %>
The first argument for all three methods is the button title, and the second one is an array of options. The title isn’t encoded, so if you’re displaying data from the end user, encode it with [[Html.encode|Html.encode]].
Input Fields
There are two groups of input methods. The ones starting with active
, which are called active inputs, and the ones not starting with it.
Active inputs take data from the model and attribute specified, while in the case of a regular input, data is specified
directly.
The most generic methods are:
type, input name, input value, options
<%- Html.input('text', 'username', user.name, {class: username}) %>
type, model, model attribute name, options
<%- Html.activeInput('text', user, 'name', {class: username}) %>
If you know the input type in advance, it’s more convenient to use the shortcut methods:
- [[Html.buttonInput]]
- [[Html.submitInput]]
- [[Html.resetInput]]
- [[Html.textInput]], [[Html.activeTextInput]]
- [[Html.hiddenInput]], [[Html.activeHiddenInput]]
- [[Html.passwordInput]] / [[Html.activePasswordInput]]
- [[Html.fileInput]], [[Html.activeFileInput]]
- [[Html.textarea]], [[Html.activeTextarea]]
Radios and checkboxes are a bit different in terms of method signature:
<%- Html.radio('agree', true, {label: 'I agree'}) %>
<%- Html.activeRadio(model, 'agree', {class: 'agreement'}) %>
<%- Html.checkbox('agree', true, {label: 'I agree'}) %>
<%- Html.activeCheckbox(model, 'agree', {class: 'agreement'}) %>
Dropdown lists and list boxes can be rendered like the following:
<%- Html.dropDownList('list', $currentUserId, ArrayHelper.map(userModels, 'id', 'name')) %>
<%- Html.activeDropDownList(users, 'id', ArrayHelper.map(userModels, 'id', 'name')) %>
<%- Html.listBox('list', $currentUserId, ArrayHelper.map(userModels, 'id', 'name')) %>
<%- Html.activeListBox(users, 'id', ArrayHelper.map(userModels, 'id', 'name')) %>
The first argument is the name of the input, the second one is the value that’s currently selected, and the third one is an array of key-value pairs, where the array key is the list value and the array value is the list label.
If you want multiple choices to be selectable, you can use a checkbox list:
<%- Html.checkboxList('roles', [16, 42], ArrayHelper.map(roleModels, 'id', 'name')) %>
<%- Html.activeCheckboxList(user, 'role', ArrayHelper.map(roleModels, 'id', 'name')) %>
If not, use radio list:
<%- Html.radioList('roles', [16, 42], ArrayHelper.map(roleModels, 'id', 'name')) %>
<%- Html.activeRadioList(user, 'role', ArrayHelper.map(roleModels, 'id', 'name')) %>
Labels and Errors
Same as inputs, there are two methods for generating form labels. Active, which takes data from the model, and non-active, which accepts data directly:
<%- Html.label('User name', 'username', {class: 'label username'}) %>
<%- Html.activeLabel(user, 'username', {class: 'label username'}) %>
In order to display form errors from a model or models as a summary, you could use:
<%- Html.errorSummary(posts, {class: 'errors'}) %>
To display an individual error:
<%- Html.error(post, 'title', {class: 'error'}) %>
Input Names and Values
There are methods to get names, ids and values for input fields based on the model. These are mainly used internally, but could be handy sometimes:
// Post[title]
console.log(Html.getInputName(post, 'title'));
// post-title
console.log(Html.getInputId(post, 'title'));
// my first post
console.log(Html.getAttributeValue(post, 'title'));
// post->authors[0]
console.log(Html.getAttributeValue(post, '[0]authors[0]'));
In the above, the first argument is the model, while the second one is the attribute expression. In its simplest form the expression is just an attribute name, but it can be an attribute name prefixed and/or suffixed with array indexes, which is mainly used for tabular input:
[0]content
is used in tabular data input to represent thecontent
attribute for the first model in tabular input;dates[0]
represents the first array element of thedates
attribute;[0]dates[0]
represents the first array element of thedates
attribute for the first model in tabular input.
In order to get the attribute name without suffixes or prefixes, one can use the following:
// dates
console.log Html.getAttributeName('dates[0]');
Styles and Scripts
There are two methods to generate tags wrapping embedded styles and scripts:
<%- Html.style('.danger { color: #f00; }', {media: 'print'}) %>
Gives you
<style media="print">.danger { color: #f00; }</style>
<%- Html.script('alert("Hello!");') %>
Gives you
<script>alert("Hello!");</script>
If you want to use an external style in a CSS file:
<%- Html.cssFile('css/ie5.css', {condition: 'IE 5'}) %>
generates
<!--[if IE 5]>
<link href="http://example.com/css/ie5.css" />
<![endif]-->
The first argument is the URL. The second one is an array of options. In addition to the regular options, you can specify:
condition
to wrap<link
in conditional comments with the specified condition. Hope you won’t need conditional comments ever ;)noscript
can be set totrue
to wrap<link
in a<noscript>
tag so it will be included only when there’s either no JavaScript support in the browser or it was disabled by the user.
To link a JavaScript file:
<%- Html.jsFile('/js/main.js') %>
Same as with CSS, the first argument specifies the URL of the file to be included. Options can be passed as the second argument.
In the options you can specify condition
in the same way as in the options for cssFile
.
Hyperlinks
There’s a method to generate hyperlinks conveniently:
<%- Html.a('Profile', `user/view/${id}`, {class: 'profile-link'}) %>
The first argument is the title. It’s not encoded, so if you’re using data entered by the user, you need to encode it with
Html.encode()
. The second argument is what will be in the href
attribute of the <a
tag.
The third argument is an array of tag attributes.
If you need to generate mailto
links, you can use the following code:
<%- Html.mailto('Contact us', 'admin@example.com') %>
Images
In order to generate an image tag, use the following:
<%- Html.img('images/logo.png', {alt: 'My logo'}) %>
generates
<img src="http://example.com/images/logo.png" alt="My logo" />
Besides aliases, the first argument can accept routes, parameters and URLs.
Lists
Unordered list can be generated like the following:
<%- Html.ul(posts, {item: function(item, index) {
return Html.tag(
'li',
this.render('post', {item: item}),
{class: 'post'}
);
}}) %>
In order to get ordered list, use Html.ol()
instead.