HTML Help Class (HTML helper)
Reference Address: http://www.yiiframework.com/doc-2.0/guide-helper-html.html
Every web app generates a lot of HTML tags, and if the tag is static, he can effectively avoid the confusion between PHP code and HTML, but when it is generated dynamically, it becomes tricky to handle, but it does not need the extra help to do it. YII provides such assistance in a form that provides a series of static methods to handle the generation of HTML tag components, as well as their options and content.
Tip: Into your tag is static you'd better use HTML directly. There is no need to call the HTML helper function again.
1. Basic Knowledgebecause building Dynamic HTML with string connections is getting faster but messy, Yii provides a way to manipulate label options and create labels based on these options.
(1) Generate tags (generating tags)
The code to generate the tag is as follows:
<?= html::tag (' P ', Html::encode ($user->name), [' class ' = ' username '])?>
The first parameter is the name of the tag.
The second parameter is the contents of the label. Note here we use Html::encode. That's because content is not automatically encoded in HTML.
The third parameter is an optional array that contains the relevant options for the HTML, in other words, the related properties of the tag. The key in the array is the property name, such as class, HREF, or target value, which corresponds to the value of the property.
The above code generates the following:
<p class= "username" >samdark</p>
In some cases you just need to start the tag or close the tag, you can use the Html::begintag () and the Html::endtag () method.
Options are used in HTML-assisted and various parts of the method are many. In all these cases, there is some additional processing that needs to be understood:
A. If the value is null, the corresponding property will not be rendered.
B. Its attribute value is a Boolean type that will be treated as a Boolean property.
C. The value of the property uses Html::encode ()for Html encoding.
D. If the value of the property is an array, it will be treated as follows:
If the property is a data property as listed in
Yii\helpers\html:: $dataAttributes,
Just like data or NG, a list of attributes will be rendered, for example,
' Data ' = [' id ' = ' 1 ', ' name ' = ' Yii ']
is generated
Data-id= "1" data-name= "Yii";
and
' Data ' = [' params ' + [' id ' = ' 1 ', ' name ' = ' yii '], ' status ' = ' OK ']
The Build
Data-params= ' {' id ': 1, ' name ': ' Yii '} ' data-status= ' OK '.
Note In the latter example, the sub-arrays are rendered in JSON format.
If the attribute is not data, he will proceed directly to json-encoded. For example
[' params ' = = [' id ' = ' 1 ', ' name ' = ' Yii ']
Generated
Params= ' {"id": 1, "name": "Yii"} '.
(2) Formatting CSS class and style (Forming CSS Classes and styles)
When establishing an option on HTML tags we often first change the default settings from what we need. In order to add or remove CSS classes,
You can use the following command:
<?php$options = [' class ' = ' btn btn-default '];if ($type = = = ' Success ') { html::removecssclass ($options, ' Btn-default '); Html::addcssclass ($options, ' btn-success ');} echo html::tag (' div ', ' pwede na ', $options);//When $type is ' success ' into//<div class= "btn btn-success" >pwede na</div >?>
in order to achieve the same purpose as style properties for styles:
<?php$options = [' style ' = = [' width ' = ' 100px ', ' height ' = ' 100px ']];//add style style= ' width:100px; height:200px; Position:absolute; " Html::addcssstyle ($options, ' height:200px; position:absolute; '); /Add Style style= "position:absolute;" Remove height and Widthhtml::removecssstyle ($options, [' width ', ' height ']); >
when using Addcssstyle () You can make an array of any key-value pairs of CSS properties like
width:100px; height:200px;.
These formats can be converted to each other by using Cssstylefromarray () and Cssstyletoarray ().
The Removecssstyle () method receives an array of parameters that list the name of the CSS property you want to remove. If only a single property
Can be specified directly as a string.
(3) encoding and decoding contents (Encoding and decoding content)
In order for content to be displayed correctly and securely in HTML, special characters in the content need to be encoded.
In PHP it is done by the htmlspecialchars and htmlspecialchars_decode functions.
The problem with using these methods directly is that you have to specify the encoding and the extra flags all the time. Because the flags are the same all the time and the encoding should match one of the applications in order to prevent security problems, YII provides two compact and simple usage methods:
<?php$username = Html::encode ($user->name); echo $userName; $decodedUserName = Html::d ecode ($userName); >
2. Forms (Forms)
Form tag processing is fairly frequent and error prone. Because of this, there is a set of methods to help deal with these problems.
Tip: Consider using ActiveForm if you use models and need to verify (validation).
(1) Create a form (Creating forms)
Form use Method BeginForm () to open the form label:
<?= html::beginform ([' order/update ', ' id ' = + $id], ' post ', [' enctype ' = ' multipart/form-data '])?>
The first parameter is the URL address of the submission. It can be specified in the form url::to () in the Yii middle, and accepts parameters that can be accepted by the parameter.
The second parameter is the way the submission is committed. The default is post.
The third parameter is the optional option for the form label. such as uploading files we need to use enctype = Multipart/form-data.
Close the form label:
<?= Html::endform ()?>
(2) button (Buttons)
In order to generate a button you can use the following code:
<?= Html::button (' Press me! ', [' class ' = ' teaser '])? ><?= Html::submitbutton (' Submit ', [' class ' = ' = ') ' Submit '])? ><?= Html::resetbutton (' Reset ', [' class ' = ' reset '])?>
the first parameter of all three methods is the button caption and the second is the option.
The title is not encoded, so if you are getting data from the end user, use it to encode Html::encode ().
(3) File Upload form (Input fields)
There are two sets of input methods below.
One is the dynamically generated fetch dynamic input and the other is not.
Dynamic inputs gets the specified data and attributes from the model, whereas the normal form specifies the input data directly.
The most commonly used two methods are as follows:
Type types, name of input, value of input, related options for input
<?= html::input (' text ', ' username ', $user->name, [' class ' = $username])?>
type, model, property name, input related options
<?= html::activeinput (' text ', $user, ' name ', [' class ' = ' + $username])?>
If you know beforehand the type of input has a quicker way:
The following are the relevant components and methods
Yii\helpers\html::buttoninput ()
Yii\helpers\html::submitinput ()
Yii\helpers\html::resetinput ()
Yii\helpers\html::textinput (), Yii\helpers\html::activetextinput ()
Yii\helpers\html::hiddeninput (), Yii\helpers\html::activehiddeninput ()
Yii\helpers\html::p asswordinput ()/Yii\helpers\html::activepasswordinput ()
Yii\helpers\html::fileinput (), Yii\helpers\html::activefileinput ()
Yii\helpers\html::textarea (), Yii\helpers\html::activetextarea ()
(4) radio button and check box
Radios and checkboxes are somewhat different in terms of methods:
<?= Html::radio (' agree ', true, [' label ' = ' I agree ']);? ><?= Html::activeradio ($model, ' agree ', [' class ' =&G T ' agreement ')? ><?= Html::checkbox (' agree ', true, [' label ' = ' I agree ']);? ><?= Html::activecheckbox ($ Model, ' agree ', [' class ' = ' agreement '])?>
(5) drop-down lists and lists
The Dropdown list and list box are rendered as follows:
<?= HTML::d ropdownlist (' 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 parameter is the name of input.
The second parameter is the value of the currently selected selected drop-down box
The third parameter is a key value for the array where the key is the value of the list, and the value of the list is the label of the lable
(6) Multi-select drop-down list
<?= html::checkboxlist (' roles ', [+], Arrayhelper::map ($roleModels, ' id ', ' name '))? ><?= Html:: Activecheckboxlist ($user, ' role ', Arrayhelper::map ($roleModels, ' id ', ' name ')?>
(7) Radio list
<?= html::radiolist (' roles ', [+], Arrayhelper::map ($roleModels, ' id ', ' name '))? ><?= Html:: Activeradiolist ($user, ' role ', Arrayhelper::map ($roleModels, ' id ', ' name ')?>
(8) tags and errors (Labels and Errors)
As input, there are two ways to generate form labels.
The dynamic is to take the value from the model, and the other is to take the value directly:
<?= Html::label (' User name ', ' username ', [' class ' = ' label username '])? ><?= Html::activelabel ($user, ' Username ', [' class ' = ' label username '])?>
To show a form error from one or more model, here's a summary you might use:
<?= html::errorsummary ($posts, [' class ' = ' Errors '])?>
To display a single error:
<?= html::error ($post, ' title ', [' class ' = ' Error '])?>
(9) Input name and value (input Names and values)
There are two ways to get the name names, IDs, and values for the model-based input field.
These are primarily used internally, but sometimes may not be handy:
<?php//Post[title]echo html::getinputname ($post, ' title ');//Post-titleecho Html::getinputid ($post, ' title ');// My first Postecho html::getattributevalue ($post, ' title ');//$post->authors[0]echo Html::getattributevalue ($post, ' [0]authors[0] ');? >
The first parameter in the above example is model, the second argument is the property expression
In its simplest form, its property name, but it may be a property name prefix and/or suffix, primarily used to index the form input array:
[0]content is used in the data list to enter the first value of the model that represents the "content" attribute in the data list;
Dates[0] represents the first attribute of the "dates" array element;
[0]dates[0] means that the first attribute of the "dates" array element corresponds to the first model entered by the form.
In order to get the property name without a prefix or suffix you can use the following form:
<?php//datesecho html::getattributename (' dates[0] ');? >
3. Styles and scripts (styles and Scripts)
There are two ways of claiming styles and scripts:
<?= Html::style ('. Danger {color: #f00;} ')? >//generates <style>.danger {color: #f00;} </style>
<?= html::script (' Alert (' hello! '); ', [' defer ' = true]);? >//will generate <script Defer>alert ("hello!"); </script>
if you want to introduce an external style file:
<?= html::cssfile (' @web/css/ie5.css ', [' condition ' = ' IE 5 '])? >//generates <!--[if IE 5]> <link href= ' Http://example.com/css/ie5.css "/><! [endif]-->
The first parameter is a URL.
The second parameter is a series of action properties. In addition to the general options, you can specify:
Condition to wrap the link with the specified conditional condition comment. I hope you never need a conditional comment.
<noscript> can be set to true to wrap <link> and <noscript> tags so will be included only if there is one in the browser
There is no support for JavaScript, or it is closed by the user.
Link JavaScript files:
<?= html::jsfile (' @web/js/main.js ')?>
parameters use the same as the CSS file, you can also set the two parameters of the second parameter.
4. Hyperlinks (Hyperlinks)
Here's a gradient way to create a hyperlink:
<?= html::a (' profile ', [' User/view ', ' id ' = ' $id], [' class ' = ' Profile-link '])?>
The first parameter is the caption. No coding, if required, you can use html::encode ().
The second parameter specifies the href attribute of the A tag. Please refer to url::to () for more details on the parameters.
Http://www.yiiframework.com/doc-2.0/guide-helper-url.html
The third parameter is the related property of the label.
If you want to generate mailto mail links:
<?= Html::mailto (' Contact us ', ' [email protected] ')?>
5. Picture (Images)
Here is the label for the resulting picture:
<?= html::img (' @web/images/logo.png ', [' alt ' = ' My logo '])? >//generate
The first parameter is the URL the second parameter is an option for the IMG tag
6. Lists List
The unordered list is generated roughly like the following code:
<?= Html::ul ($posts, [' Item ' = function ($item, $index) { return Html::tag ( ' Li ', $this->render ( ' Post ', [' item ' = + $item]), [' class ' = ' post '] );}]) ?>
The ordered list is Html::ol () instead of the upper line.
Yii Learning Note VI (HTML generation Helper API translation)