Skip to content

HTMLTag

Mistralys edited this page Jan 7, 2022 · 7 revisions

The HTMLTag helper class can be used to generate individual HTML tags with an easy to use, chainable object-oriented API.

Quickstart

use AppUtils;

echo HTMLTag::create('code')
   ->addClass('preformatted')
   ->id('code-snippet')
   ->attr('data-format', 'pretty')
   ->addText('Content here');

Output (formatted for readability):

<code class="preformatted" id="code-snippet" data-format="pretty">
    Content here
</code>

Examples

Adding properties

use AppUtils;

echo HTMLTag::create('select')
   ->name('product')
   ->prop('multiple')
   ->renderOpen();

Output:

<select name="product" multiple>

Self-closing tags

use AppUtils;

echo HTMLTag::create('link')
    ->attr('rel', 'stylesheet')
    ->href('/path/to/stylesheet.css')
    ->setSelfClosing();

Output:

<link rel="stylesheet" href="/path/to/stylesheet.css">

When generating XHTML, the slash can be enabled globally:

use AppUtils;

HTMLTag::getGlobalOptions()->setSelfCloseSlash();

echo HTMLTag::create('link')
    ->attr('rel', 'stylesheet')
    ->href('/path/to/stylesheet.css')
    ->setSelfClosing();

Output:

<link rel="stylesheet" href="/path/to/stylesheet.css"/>

Canned tags

The CannedTags utility class has a number of predefined methods for commonly used tags, which can be used to quickly create these tags.

use AppUtils\HTMLTag\CannedTags;

echo CannedTags::p('Paragraph')
    ->addClass('abstract');

Output:

<p class="abstract">Paragraph</p>

Building tag contents

The contents of tags are based on a StringBuilder instance. The following methods are built in to add contents:

  • setContent() Sets (and replaces) the current content
  • addText() Appends a bit of text (with space at the end)
  • appendHTML() Appends HTML code (without space)

If this is not sufficient, use the $content property to work directly with the StringBuilder instance:

use AppUtils;

$tag = HTMLTag::create('div');

$tag->content
    ->note()
    ->t('Read the documentation!');

echo $tag;

New here?

Have a look at the overview for a list of all helper classes available in the package.

Table of contents

Find the current page in the collapsible "Pages" list above, and expand the page, to view a table of contents.

Clone this wiki locally