Saltar al contenido
MovieMaster

Desarrolladores: plugins y themes

Template engine (.tpl)

8 min de lectura 12 apartados

En esta página

Site pages, admin panel pages, and plugin views are written in .tpl files. The syntax is similar to Blade (Laravel): {{ }} to print, directives starting with @, and layout inheritance. Each template is compiled once to plain PHP and stored in content/cache/views/, so it costs nothing at runtime.

Printing values #

SyntaxWhat it does
{{ $title['title'] }}Prints escaped, via e(). null prints nothing. Always use it when the value comes from the database or from a visitor.
{!! $html !!}Prints unescaped. Only for HTML you control yourself or that a helper already returns (img(), player(), wordmark(), $seo->render()).
{{-- comment --}}Comment: never reaches the HTML.
@{{ something }}Prints the literal {{ something }} (for JavaScript with its own templating).
@@ifPrints the literal @if.
@verbatim … @endverbatimEverything inside comes out as-is, uncompiled.
html
<h1>{{ $title['title'] }}</h1>
<p class="synopsis">{{ str_limit($title['overview'], 200) }}</p>
{!! img($title['poster'], 'poster', ['alt' => $title['title'], 'priority' => true]) !!}

Conditionals #

html
@if ($title['rating'] >= 8)
  <span class="top">{{ __('common.top_rated') }}</span>
@elseif ($title['rating'] > 0)
  {!! rating_badge($title['rating']) !!}
@else
  <span>—</span>
@endif

@unless (empty($title['tagline']))
  <p class="tagline">{{ $title['tagline'] }}</p>
@endunless

@isset($season)
  <h2>{{ $season['name'] }}</h2>
@endisset

@empty($related)
  <p>{{ __('common.nothing_here') }}</p>
@endempty
DirectiveEquivalent to
@if (expr) · @elseif (expr) · @else · @endifPHP's if
@unless (expr) · @endunlessif (!expr)
@isset($var) · @endissetif (isset($var))
@empty($var) · @endemptyif (empty($var))
@hasSection('name') · @endifDid any template define that section?

Loops #

html
@foreach ($titles as $t)
  <a class="cd{{ $loop->first ? ' first' : '' }}" href="{{ $t['url'] }}">
    <span class="n">{{ $loop->iteration }}</span>
    {{ $t['title'] }}
  </a>
@endforeach

@forelse ($people as $p)
  <li>{{ $p['name'] }}</li>
@empty
  <li>{{ __('common.no_results') }}</li>
@endforelse

@for ($i = 1; $i <= 10; $i++) … @endfor
@while ($cond) … @endwhile

@break and @continue cut or skip, and accept a condition: @break($loop->iteration > 5), @continue(empty($t['poster'])).

The $loop variable #

Inside @foreach and @forelse you have $loop:

PropertyValue
$loop->iterationCurrent pass, starting at 1.
$loop->indexCurrent pass, starting at 0.
$loop->first / $loop->lastIs this the first or last pass?
$loop->odd / $loop->evenIs this pass odd or even?
$loop->countTotal number of items (null if they can't be counted, like a generator).
$loop->remainingHow many are left after this one.
$loop->depthNesting level (1 = outer loop).
$loop->parentThe outer loop's $loop, inside nested loops.

A common pattern: giving load priority only to the first images.

html
@foreach ($titles as $t)
  {!! img($t['poster'], 'poster', ['alt' => $t['title'], 'priority' => $loop->iteration <= 2]) !!}
@endforeach

Layouts and sections #

A page extends a layout and fills in its sections:

html
{{-- templates/new-releases.tpl --}}
@extends('layout')

@section('content')
  <main id="main" class="wrap">
    <h1>{{ $heading }}</h1>
    @include('partials/grid', ['titles' => $titles, 'lcp' => 8])
    {!! pagination($pagination, '/new-releases') !!}
  </main>
@endsection
html
{{-- templates/layout.tpl (simplified) --}}
<!DOCTYPE html>
<html lang="{{ $site['lang'] }}">
<head>
{!! $seo->render() !!}
<style>{!! inline_css('critical.css') !!}</style>
@hook('head')
</head>
<body>
@hook('body_open')
@hook('before_content')
@yield('content')
@hook('after_content')
@hook('footer')
@hook('body_close')
</body>
</html>
DirectiveWhat it does
@extends('layout')This template is rendered inside layout.tpl. Anything you write outside the sections is discarded.
@section('name') … @endsectionDefines a section's content.
@section('name', $value)One-line short section. The value is escaped.
@yield('name', 'default')Prints a section (or the default value if nobody defined it).
@section('name') … @showIn the layout: defines default content and prints it right there.
@parentInside the child page's section: inserts the content the layout defined with @section … @show there.
html
{{-- layout --}}
@section('sidebar')
  <nav>{{ __('common.menu') }}</nav>
@show

{{-- page --}}
@section('sidebar')
  @parent
  <aside>Something else</aside>
@endsection

Layouts can be chained: a template extends title, which in turn extends layout. That's how season.tpl works in Cinema: just @extends('title').

Including partials #

html
@include('partials/card', ['t' => $title, 'priority' => true])
@includeIf('partials/promo')
  • The partial receives all the variables of the template that includes it, plus whatever you pass it (those win). The exception is $loop, which isn't passed to the partial: if you need it, pass it yourself (['n' => $loop->iteration]).
  • @include fails if the partial doesn't exist. @includeIf prints nothing in that case: use it for optional partials a child theme might add.

Hooks in templates #

DirectiveEquivalent toUse
@hook('name', $arg1, …)do_action('name', $arg1, …)A point where plugins print HTML.
@filter('name', $value, …)echo apply_filters('name', $value, …)A value plugins can change. Prints unescaped: the starting value must already be safe HTML.
html
<div class="actions">
  @hook('title_actions', $title)
</div>

<p class="notice">@filter('my_theme_notice', e(__('my_theme.notice')), $title)</p>

If you add your own hooks to a theme, prefix them (my_theme_…) and document them. The hooks every theme must fire (head, body_open, nav_items, before_content, after_content, footer, body_close, player_before, player_after) are in Creating themes.

Translations #

html
{{ __('theme.watch_now') }}
{{ __('my_theme.welcome', ['name' => $site['name']]) }}
{{ _n('common.seasons_count', count($seasons)) }}
@lang('my_theme.welcome', ['name' => $site['name']])
{{ __('my-plugin::button') }}

@lang(...) is the same as {{ __(...) }}: it prints escaped. If a key doesn't exist in the page's language, it's looked up in the site's default language, then in English, and if it's still not found, the key itself is printed.

Translations are organized differently in themes and plugins:

ExtensionFilesHow they're requested
Themelang/es.php, lang/en.php… return an array that merges with the core's strings.With a dot: 'my_theme' => ['welcome' => 'Hello'] → __('my_theme.welcome'). Use your own group so you don't collide with anyone.
Plugin (spec 1)lang/es.php… registered with $plugin->lang() under its own domain.With the domain: __('my-plugin::button').

Since a theme merges with the core, it can also override core strings: a lang/en.php with 'theme' => ['watch_now' => 'Play'] changes that button across the whole site. Child theme files load after the parent's, so they win.

PHP, JSON, and forms #

html
@php
  $ap = $site['appearance'] ?? [];
  $isSeries = ($title['type'] ?? '') === 'series';
@endphp

<script type="application/json" id="my-data">@json(['id' => $title['id'], 'url' => $title['url']])</script>
DirectiveWhat it does
@php … @endphpA block of PHP. Use it to prepare variables, not for heavy logic: queries belong in the controller or in a template_data filter.
@json($value)Safe JSON to drop into HTML (escapes <, >, &, quotes).
@csrf<input type="hidden" name="_token"> for the admin panel. It's useless on the public site (the page is cached): see public forms.
@method('PUT')Hidden _method field to send PUT or DELETE from a form.

Fragment caching #

html
@cache('my-theme:footer-genres:' . current_lang(), 3600)
  <ul>
    @foreach (app(\MovieMaster\Content\Repositories\TermRepository::class)->all('genre', null, 'name', 20, true) as $g)
      <li><a href="{{ $g['url'] }}">{{ $g['name'] }}</a></li>
    @endforeach
  </ul>
@endcache

@cache('key', seconds) stores the block's HTML in the object cache (cache()) and reuses it until it expires. It's useful for expensive chunks repeated across many pages. The key must include everything that changes the result (the language, at least). This cache is not purged when content changes: pick short TTLs or use keys that change on their own.

How templates are resolved #

Names have no extension and use / for folders:

NameWhere it's looked up
title, partials/cardtemplates/ of the active theme → its parent → Cinema (core/themes/default/templates). The first one that exists wins.
my-plugin::boxFolders registered by the plugin with $plugin->views(__DIR__ . '/views').
admin::layoutAdmin panel views.

That's why a child theme only needs the templates it changes: the rest comes from the parent or from Cinema. There's only one level of parent; a theme that's a child of a child doesn't inherit from the grandparent (but it always falls back to Cinema).

From PHP it's rendered with view('my-plugin::box', ['titles' => $items]), which returns the HTML as text.

Available variables #

All public templates receive:

VariableContents
$sitename, tagline, url, lang, langs, appearance (colors, logo, custom CSS…), footer_pages, social_links.
$seoThe page's PageSeo object. {!! $seo->render() !!} prints <title>, meta tags, canonical, hreflang, and JSON-LD.
$templateThe template's name (home, title, episode…). Useful in the layout to mark the active menu item.

Each page's own variables ($title, $titles, $pagination…) are in Creating themes. A plugin can add or change variables before rendering with the template_data filter.

Compilation and debugging #

  • Every .tpl is compiled to PHP in content/cache/views/ the first time, and recompiled whenever you change the file. With app.debug on, it always compiles.
  • php bin/console.php cache:clear deletes compiled templates, the object cache (including @cache fragments), and the page cache. Compiled templates and the page cache are also cleared when activating, deactivating, or updating an extension.
  • A template error goes into content/logs/app.log. theme:check compiles every template in the theme and runs php -l on the result, so syntax errors show up before you publish.
  • Always write PHP blocks as @php … @endphp. Don't use the short form @php(...): if an @endphp block follows later, the compiler merges them and the template breaks.
  • Directives recognize nested parentheses (@if (in_array($x, ['a', 'b']))). An @word that isn't a known directive is left as-is, so a @media inside <style> causes no issues.

¿Te quedó alguna duda?

Escríbenos y te ayudamos con tu caso.

Hablar con nosotros
¿Hablamos?