Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

View helpers

A view helper is a small function called in a view script through $this: $this->escapeHtml(), $this->url(). Helpers take over repetitive work: building a link, including a stylesheet, printing a shared piece of markup. You do not create them — they come with the laminas-view package.

The url() helper builds an address from a route name:

<!-- module/Blog/view/blog/post/index.phtml -->
<a href="<?= $this->url('blog/add') ?>">New post</a>

The page gets a link to /blog/add. Route parameters go in the second argument, the query string in the third:

<!-- module/Blog/view/blog/post/index.phtml -->
<ul>
    <?php foreach ($this->posts as $post): ?>
        <li>
            <a href="<?= $this->url('blog/view', ['id' => $post['id']]) ?>">
                <?= $this->escapeHtml($post['title']) ?>
            </a>
        </li>
    <?php endforeach; ?>
</ul>
 
<a href="<?= $this->url('blog', [], ['query' => ['page' => 2]]) ?>">Next</a>

The post titles became links such as /blog/1, and the last link leads to /blog?page=2.

Files: basePath

Styles, scripts and images live in the public folder. The basePath() helper prepends the site's base address to a path:

<img src="<?= $this->basePath('img/logo.png') ?>" alt="Logo">

The file public/img/logo.png opens even when the site is hosted in a subfolder rather than at the domain root.

Pieces of a view: partial

A repeated piece of markup is moved into a separate file. Create module/Blog/view/blog/post/_card.phtml (the underscore in the name is a common mark for "a piece, not a page"):

<!-- module/Blog/view/blog/post/_card.phtml -->
<article>
    <h2><?= $this->escapeHtml($this->post['title']) ?></h2>
    <a href="<?= $this->url('blog/view', ['id' => $this->post['id']]) ?>">Read</a>
</article>

Now this piece can be called from any view script:

<!-- module/Blog/view/blog/post/index.phtml -->
<div class="posts">
    <?php foreach ($this->posts as $post): ?>
        <?= $this->partial('blog/post/_card', ['post' => $post]) ?>
    <?php endforeach; ?>
</div>

The first argument is the template name without the extension, the second holds the variables for it. A partial sees only what was passed to it.

Other helpers

HelperWhat it does
headTitle('Blog')The window title
headLink()Stylesheets in head
headScript(), inlineScript()Scripts
headMeta()meta tags
partialLoop('name', $items)Renders a partial for each item of a list
escapeHtml(), escapeHtmlAttr()Escaping

Common mistake

An address typed by hand — href="/blog/5" — stops working as soon as the route changes or the site moves to a subfolder. Always build links to pages with url() and links to files with basePath().

Thanks for reading!

Donate to the site — we work hard for you.