Giter Site home page Giter Site logo

html's Introduction

Yii

Yii HTML


Latest Stable Version Total Downloads Build Status Scrutinizer Code Quality Code Coverage Mutation testing badge static analysis psalm-level type-coverage

The package provides various tools to help with dynamic server-side generation of HTML:

  • Tag classes A, Address, Article, Aside, Audio, B, Body, Br, Button, Caption, Col, Colgroup, Datalist, Div, Em, Fieldset, Footer, Form, H1, H2, H3, H4, H5, H6, Header, Hr, Hgroup, Html, I, Img, Input (and specialized Checkbox, Radio, Range, File), Label, Legend, Li, Link, Meta, Nav, Noscript, Ol, Optgroup, Option, P, Picture, Script, Section, Select, Small, Source, Span, Strong, Style, Table, Tbody, Td, Textarea, Tfoot, Th, Thead, Title, Tr, Track, Ul, Video.
  • CustomTag class that helps to generate custom tag with any attributes.
  • HTML widgets ButtonGroup, CheckboxList and RadioList.
  • All tags content is automatically HTML-encoded. There is NoEncode class designed to wrap content that should not be encoded.
  • Html helper that has static methods to generate HTML, create tags and HTML widget objects.

Note that for simple static-HTML cases, it is preferred to use HTML directly.

Requirements

  • PHP 8.0 or higher.

Installation

The package could be installed with Composer:

composer require yiisoft/html

General usage

<?php
use Yiisoft\Html\Html;
use Yiisoft\Html\Tag\Meta;
?>

<?= Meta::pragmaDirective('X-UA-Compatible', 'IE=edge') ?>
<?= Meta::data('viewport', 'width=device-width, initial-scale=1') ?>

<?= Html::cssFile(
    'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
    [
        'integrity' => 'sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T',
        'crossorigin' => 'anonymous'
    ]
) ?>
<?= Html::cssFile('/css/site.css', ['rel' => 'stylesheet']) ?>

<?= Html::openTag('footer', ['class' => 'footer']) ?>
    <?= Html::openTag('div', ['class' => 'container flex-fill']) ?>
        <?= Html::p('', ['class' => 'float-left']) ?>
        <?= Html::p()
            ->replaceClass('float-right')
            ->content(
                'Powered by ',
                Html::a(
                    'Yii Framework',
                    'https://www.yiiframework.com/',
                    ['rel' => 'external']
                )
            ) ?>
    <?= Html::closeTag('div') ?>
<?= Html::closeTag('footer') ?>

Tag objects usage

Tag classes allow working with a tag as an object and then get an HTML code by using render() method or type casting to string. For example, the following code:

echo \Yiisoft\Html\Tag\Div::tag()
    ->content(
        \Yiisoft\Html\Tag\A::tag()
            ->mailto('[email protected]')
            ->content('contact us')
            ->render()
    )
    ->encode(false)
    ->id('ContactEmail')
    ->replaceClass('red');

... will generate the following HTML:

<div id="ContactEmail" class="red"><a href="mailto:[email protected]">contact us</a></div>

Generating custom tags

To generate custom tags, use the CustomTag class. For example, the following code:

echo \Yiisoft\Html\Tag\CustomTag::name('b')
    ->content('text')
    ->attribute('title', 'Important');

... will generate the following HTML:

<b title="Important">text</b>

Encoding tags content

By default, stringable objects that implement \Yiisoft\Html\NoEncodeStringableInterface are not encoded, everything else is encoded.

To change this behavior use encode() method passing one of the following values:

  • null: default behavior;
  • true: any content is encoded;
  • false: nothing is encoded.

Note: all bundled tags and widgets implement \Yiisoft\Html\NoEncodeStringableInterface interface and are not encoded by default when passed as content. Their own content is encoded.

Examples:

// <b>&lt;i&gt;hello&lt;/i&gt;</b>
echo Html::b('<i>hello</i>');

// <b><i>hello</i></b>
echo Html::b('<i>hello</i>')->encode(false);

// <b><i>hello</i></b>
echo Html::b(Html::i('hello'));

// <b>&lt;i&gt;hello&lt;/i&gt;</b>
echo Html::b(Html::i('hello'))->encode(true);

In order to mark a string as "do not encode" you can use \Yiisoft\Html\NoEncode class:

// <b><i>hello</i></b>
echo Html::b(NoEncode::string('<i>hello</i>'));

HTML widgets usage

There are multiple widgets that do not directly represent any HTML tag, but a set of tags. These help to express complex HTML in simple PHP.

ButtonGroup

Represents a group of buttons.

echo \Yiisoft\Html\Widget\ButtonGroup::create()
   ->buttons(
       \Yiisoft\Html\Html::resetButton('Reset Data'),
       \Yiisoft\Html\Html::resetButton('Send'),
   )
   ->containerAttributes(['class' => 'actions'])
   ->buttonAttributes(['form' => 'CreatePost']);

Result will be:

<div class="actions">
<button type="reset" form="CreatePost">Reset Data</button>
<button type="reset" class="primary" form="CreatePost">Send</button>
</div>

CheckboxList

Represents a list of checkboxes.

echo \Yiisoft\Html\Widget\CheckboxList\CheckboxList::create('count')
    ->items([1 => 'One', 2 => 'Two', 5 => 'Five'])
    ->uncheckValue(0)
    ->value(2, 5)
    ->containerAttributes(['id' => 'main']);

Result will be:

<input type="hidden" name="count" value="0">
<div id="main">
<label><input type="checkbox" name="count[]" value="1"> One</label>
<label><input type="checkbox" name="count[]" value="2" checked> Two</label>
<label><input type="checkbox" name="count[]" value="5" checked> Five</label>
</div>

RadioList

Represents a list of radio buttons.

echo \Yiisoft\Html\Widget\RadioList\RadioList::create('count')
    ->items([1 => 'One', 2 => 'Two', 5 => 'Five'])
    ->uncheckValue(0)
    ->value(2)
    ->containerAttributes(['id' => 'main'])
    ->render();

Result will be:

<input type="hidden" name="test" value="0">
<div id="main">
<label><input type="radio" name="test" value="1"> One</label>
<label><input type="radio" name="test" value="2" checked> Two</label>
<label><input type="radio" name="test" value="5"> Five</label>
</div>

Html helper usage

Html helper methods are static so usage is:

echo \Yiisoft\Html\Html::a('Yii Framework', 'https://www.yiiframework.com/');

Overall the helper has the following method groups.

Creating tag objects

Custom tags

  • tag
  • normalTag
  • voidTag

Base tags

  • b
  • div
  • em
  • i
  • hr
  • meta
  • p
  • br
  • script
  • noscript
  • span
  • strong
  • small
  • style
  • title

Media tags

  • img
  • picture
  • audio
  • video
  • track
  • source

Heading tags

  • h1
  • h2
  • h3
  • h4
  • h5
  • h6

Section tags

  • html
  • body
  • article
  • section
  • nav
  • aside
  • hgroup
  • header
  • footer
  • address

List tags

  • ul
  • ol
  • li

Hyperlink tags

  • a
  • mailto

Link tags

  • link
  • cssFile
  • javaScriptFile

Form tags

  • button
  • buttonInput
  • checkbox
  • file
  • datalist
  • fieldset
  • fileInput
  • form
  • hiddenInput
  • input
  • label
  • legend
  • optgroup
  • option
  • passwordInput
  • radio
  • resetButton
  • resetInput
  • select
  • submitButton
  • submitInput
  • textInput
  • textarea

Table tags

  • table
  • caption
  • colgroup
  • col
  • thead
  • tbody
  • tfoot
  • tr
  • th
  • td

Generating tag parts

  • openTag
  • closeTag
  • renderTagAttributes

Creating HTML widget objects

  • radioList
  • checkboxList

Working with tag attributes

  • generateId
  • getArrayableName
  • getNonArrayableName
  • normalizeRegexpPattern

Encode and escape special characters

  • encode
  • encodeAttribute
  • encodeUnquotedAttribute
  • escapeJavaScriptStringValue

Working with CSS styles and classes

  • addCssStyle
  • removeCssStyle
  • addCssClass
  • removeCssClass
  • cssStyleFromArray
  • cssStyleToArray

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii HTML is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

html's People

Contributors

abdulmannans avatar alien-art avatar amolkumargupta avatar arhell avatar arogachev avatar dependabot-preview[bot] avatar dependabot[bot] avatar devanych avatar dood- avatar fantom409 avatar gerych1984 avatar jacobbudin avatar luizcmarin avatar mister-42 avatar roxblnfk avatar rustamwin avatar samdark avatar sankaest avatar soodssr avatar stylecibot avatar terabytesoftw avatar viktorprogger avatar vjik avatar xepozz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html's Issues

Expand readme with "why using the package" section

Currently there are simple examples only so it makes people wonder if the pacakge is needed at all or simple HTML/PHP templates are better to be used. Need to provide use cases where the package gives better results (complex generated HTML) and suggest that for simple stuff direct usage of HTML tags is better.

[Community poll / discussion] Generating HTML via Yii helpers

Do you use or going to use Yii to generate HTML? This means using stuff like:

Html::a('Text', 'https://example.com');

Instead of

<a href="https://example.com">Text</a>

As we all know JS frameworks evolved dramatically since Yii 2 times, and now situation is different. Frameworks like Yii are often used only to build REST APIs. Using classic approach still has it own benefits and can be used for MVP, low budget projects and so on. This does not mean that this feature and widgets based on it will be abandoned, but rather the focus can be shifted on more important backend related packages.

๐Ÿ‘ - Use / going to use
๐Ÿ‘Ž - Do not use / not going to use
๐Ÿค™ - It depends on a project (you can write details in a comment)

Feel free to share you thoughts and ideas.

Cleaning proposal

  • Clean to Url::to, Yii::$app dependencies.
  • Remove the functions with models, and separate them, just leave the basic html.

If you agree I can do it,

Regards,

Refactoring file input

  • Input::file() returns File instead of Input
  • remove Html::fileInput()
  • remove Input::fileControl()

Add methods `addAttributes()`

All methods with names attributes(), replaceAttributes() mark as depricated and create new methods addAttrbutes() and similar for more clearly.

Related issue:

HTMX support?

I've got on the HTMX boat recently (apparently with a big chunk of the industry) and I think it's a match made in heaven for Yii framework, considering the renderPartial functionality built-in.

Would a contribution with some helpers and first-class support be accepted?

I'm also thinking on putting it on yii2, given that Pjax is already there... we would revive the framework use-cases so easily given the excellent capabilities of Yii to generate HTML with GridView.

Cheers,
R

The implicit logic of Html::escapeJsRegularExpression

Now function work with correct regexps:

Html::escapeJsRegularExpression('/([a-z0-9-]+)/Ugimex'); // /([a-z0-9-]+)/gim
Html::escapeJsRegularExpression('/mag/imgx'); // /mag/img

... and with regexps without delimiters, but with brackets:

Html::escapeJsRegularExpression('([a-z0-9-]+)'); // /[a-z0-9-]+/

... and NOT WORK with regexps without delimiters and withour brackets:

Html::escapeJsRegularExpression('(a)bc'); // /a)b/
Html::escapeJsRegularExpression('.*'); // empty string

I see two variants:

Variant one

Allow use method only with correct regexps with delimiters:

Html::escapeJsRegularExpression('/([a-z0-9-]+)/Ugimex'); // /([a-z0-9-]+)/gim
Html::escapeJsRegularExpression('/mag/imgx'); // /mag/img
Html::escapeJsRegularExpression('([a-z0-9-]+)'); // InvalidArgumentException
Html::escapeJsRegularExpression('(a)bc'); // InvalidArgumentException
Html::escapeJsRegularExpression('.*'); // InvalidArgumentException

Variant two

All regexps without delimiters wrap to /:

Html::escapeJsRegularExpression('/([a-z0-9-]+)/Ugimex'); // /([a-z0-9-]+)/gim
Html::escapeJsRegularExpression('/mag/imgx'); // /mag/img
Html::escapeJsRegularExpression('([a-z0-9-]+)'); // /([a-z0-9-]+)/
Html::escapeJsRegularExpression('(a)bc'); // /(a)bc/
Html::escapeJsRegularExpression('.*'); // /.*/

update irc link

What steps will reproduce the problem?

What is the expected result?

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

Problem with use $options at the same time for HTML attributes and additional settings

Using $options at the same time for HTML attributes and additional settings it's not clear. For example:

Html::radio('agree', false, [
	'label' => 'I agree', // Option
	'uncheck' => 0, // Option
	'id'=> 'UserAgree', // HTML attribute
	'class' => 'input-radio', // HTML attribute
]);

When resolved issue #42 for all tags added option encode. That is for all tags in one parameter will be mixed HTML attributes and options.

Maybe make for tags separately classes (with method __toString()) with specific options as methods and separately array parameter for HTML attributes. For more easy migrate for yii2 we can leave in helper Html methods for tags, For example:

echo (new P('hello, <b>world</b>', ['id' => 'Title']))->notEncode();
echo Html::p('hello, <b>world</b>', ['id' => 'Title']))->notEncode();

echo (new InputRadio('agree', false, [
	'id'=> 'UserAgree',
	'class' => 'input-radio',
))
->uncheck(0)
->withLabel('I agree');

Seems this is will be more comfortable using. Suggestions in IDE will be help.

But this will entail an increase count of objects, in some cases a significant. I don't know if this will be a problem for PHP7.4+...

What you think?

Bug in method Html::escapeJsRegularExpression()

What steps will reproduce the problem?

Html::escapeJsRegularExpression('([igm]+)');

What is the expected result?

/[igm]+/

What do you get instead?

/[igm]+/igm

Additional info

Q A
Version dev
PHP version 7.4
Operating system Win10

Broken BaseHtml::getAttributeValue()

What steps will reproduce the problem?

This code based on http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html and previously worked correctly.
Broken in yiisoft/yii2@3fcc269
Method getAttributeValue()

Model

class Blog extends ActiveRecord
{
    public static function tableName()
    {
        return 'blog';
    }

    public function rules()
    {
        return [
            [['files'], 'image', 'extensions' => 'png, jpg', 'minFiles' => 2, 'maxFiles' => 10],
        ];
    }

   ...

Controller

...

public function actionIndex()
{
    $model = new Blog();

    if ($model->load(Yii::$app->request->post())) {

        // getInstances return array of files
        $model->files = UploadedFile::getInstances($model, 'files');

        if ($model->save()) {
            if ($model->files) {
                // save files..
            }
            $this->redirect(['index']);
        }
    }

    return $this->render('upload_form', [
        'model' => $model,
    ]);
}

View

<?php $form = ActiveForm::begin([
    'options' => [
        'enctype' => 'multipart/form-data',
    ],
]); ?>

    <?= Html::activeFileInput($model, 'files[]', [
        'id' => 'upload-file',
        'multiple' => true,
        'accept' => 'image/*',
    ]); ?>

<?php ActiveForm::end(); ?>

We are submitting form with empty file input.

What is the expected result?

Model has errors ('minFiles' => 2) and form rendered again.

What do you get instead?

PHP Notice โ€“ yii\base\ErrorException
Array to string conversion

in /var/www/child/vendor/yiisoft/yii2/helpers/BaseHtml.php
line 537

$options['value'] = $value === null ? null : (string) $value;

Additional info

Q A
Yii version 2.0.10-dev
PHP version 7.0.8-0ubuntu0.16.04.2
Operating system Ubuntu 16.04

Add not encode value object

We can use VO implement NoEncodeStringableInterface when need not encode string.

For example:

Html::b(NoEncode::string($label));

Remove psalm type `HtmlAttributes`

Annotations @psalm-param HtmlAttributes|array<empty, empty> $attributes in public methods required obsessive actions in userland: often for attributes used simple non-typed array.

update src folder links

What steps will reproduce the problem?

http=>https

What is the expected result?

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.