Saltar al contenido
MovieMaster

Desarrolladores: plugins y themes

Building themes

5 min de lectura 17 apartados

En esta página

How to build a theme for MovieMaster: the folder structure, child themes, theme.json, functions.php, templates and their variables, helpers, the required hooks, CSS and JavaScript with their budgets, and the contracts plugins expect. The .tpl template syntax has its own guide: templates.

Full theme or child theme #

There are two ways to build a theme:

TypeWhat it isWhen to choose it
Child themeDeclares "parent": "default" (or another theme) and only brings what it changes: a few templates, some CSS, some text. Everything else is inherited.Almost always. You get the parent's improvements for free on every update.
Full themeNo parent. Brings its own layout.tpl, its own critical CSS, and its own JavaScript.When the design doesn't resemble any theme that ships with the CMS.

The bundled themes are Cinema (default, the base theme), Nébula (nebula), and Lumen (lumen). Nébula and Lumen are children of Cinema: they override layout.tpl, home.tpl, title.tpl, episode.tpl, and a few partials, and bring their own critical.css. They're the best example of a large child theme.

Theme structure #

text
content/themes/<slug>/
  theme.json              spec 1 manifest
  screenshot.png          880×660, under 300 KB
  functions.php           optional: theme hooks
  lang/                   optional: es.php, en.php…
  templates/
    layout.tpl            skeleton for every page
    home.tpl               home page
    titles.tpl            movie, series, and year listings
    title.tpl              movie or series detail page
    season.tpl             season
    episode.tpl             episode
    genres.tpl  tags.tpl   genre and tag indexes
    term.tpl               a genre or a tag
    people.tpl  person.tpl
    search.tpl  page.tpl  mylist.tpl  offline.tpl
    errors/error.tpl      errors (or errors/404.tpl, errors/500.tpl…)
    pages/<template>.tpl  optional: templates selectable for pages
    partials/             card, row, grid, more, person, episodes, sort
  assets/
    critical.css          CSS inlined on every page
    main.js               main module
    player.js lists.js search.js sw.js
    brand/
    critical.extra.css    child themes only
    child.js              child themes only

In a child theme everything is optional except theme.json and screenshot.png. Every file you add replaces the parent's file of the same name; whatever you don't add keeps coming from the parent.

The folder name is the slug and must match the one in theme.json. A theme is activated in Admin → Appearance → Themes. If the same slug exists in both core/themes/ and content/themes/, the folder with the newer version is used.

Create a theme with make:theme #

bash
php bin/console.php make:theme my-theme --name="My Theme" --parent=default

Generates a child theme in content/themes/my-theme/ with:

  • A theme.json with spec: 1, version 0.1.0, the parent, requires.core pinned to the current minor version, and the stable update channel.
  • A placeholder screenshot.png (needs PHP's GD extension; replace it before publishing).
  • An empty, commented functions.php.
  • An empty templates/: until you copy a template, everything comes from the parent.
  • assets/critical.extra.css for your extra CSS.

Other options: --description=, --author=, --license=, and --force (overwrites the generated files if the theme already exists). It doesn't create child.js: every byte counts against the JavaScript budget, so only add it if you need it.

For a full theme, copy core/themes/default to content/themes/<your-slug>, change slug and name in theme.json, and remove parent.

The normal workflow for a child theme is to copy from the parent only the template you want to change (core/themes/default/templates/title.tpl → content/themes/my-theme/templates/title.tpl), edit it, and check it with theme:check.

theme.json #

json
{
    "$schema": "https://moviemaster.dev/schema/theme-v1.json",
    "spec": 1,
    "name": "My Theme",
    "slug": "my-theme",
    "version": "1.0.0",
    "parent": "default",
    "author": { "name": "Your studio", "url": "https://your-studio.com" },
    "license": "proprietary",
    "description": "Home page with a carousel and two-column detail pages.",
    "descriptions": { "en": "Home page with a carousel and two-column detail pages." },
    "requires": { "core": "^0.9", "php": ">=8.2" },
    "screenshot": "screenshot.png",
    "supports": ["custom-colors", "custom-logo", "pwa", "series", "mylist"],
    "contracts": ["player@1", "mylist@1", "install@1", "i18n@1"],
    "settings": [
        { "key": "hero_autoplay", "type": "checkbox", "label": "Autoplay carousel", "default": true }
    ],
    "budget": { "inline_css": 20480, "js_initial": 5120 }
}

The fields are the same as for a plugin, with three that are specific to themes: parent, screenshot, and budget. Each one is explained in the manifest reference.

Theme settings #

Each entry in settings appears under Admin → Settings, in the "Theme options · My Theme" group, only while the theme is active. The types are the same as for plugins (text, textarea, number, checkbox, select, color, url, list, media, secret, info).

The value is stored as theme.<slug>.<key>, so you read it with setting():

html
@if(setting('theme.my-theme.hero_autoplay', true))
  <div class="hero" data-autoplay>…</div>
@endif

functions.php #

This is the theme's PHP entry point. It loads on every request, after the active plugins (so you can use their functions and hooks), the parent's first and then the child's. It runs inside an isolated function: it doesn't receive variables, but it has access to all the global functions and hooks.

php
<?php
// content/themes/my-theme/functions.php

// A class on <body> based on the template
add_filter('body_class', function (string $classes): string {
    return $classes . ' my-theme';
});

// Five related titles instead of whatever the parent brings
add_filter('related_limit', fn () => 5);

// Extra data for a specific template
add_filter('template_data', function (array $data, string $template): array {
    if ($template === 'home') {
        $data['featured'] = setting('theme.my-theme.featured', '');
    }
    return $data;
}, 10, 2);

// Something in the <head> on every page
add_action('head', function (): void {
    echo '<meta name="color-scheme" content="dark">';
});

If functions.php throws an exception, the error is logged and the site keeps working with the theme minus those changes. Don't use it to create tables or store data: that's a plugin's job.

Translations #

A theme's lang/es.php, lang/en.php… files return an array that merges with the core's strings (they don't have their own domain). Group your text under a key named after your theme:

php
<?php
// lang/en.php
return [
    'my_theme' => [
        'watch_trailer' => 'Watch trailer',
        'seasons'       => ':n seasons',
    ],
    // Override a core string site-wide:
    'theme' => [
        'watch_now' => 'Play',
    ],
];
html
{{ __('my_theme.watch_trailer') }}
{{ __('my_theme.seasons', ['n' => count($seasons)]) }}

The parent's files load before the child's, so the child wins. If a key is missing in the page's language, the site's default language is used, then English. More details in templates.

Theme templates #

Every public page is rendered with a fixed-name template. All of them extend layout with @extends('layout') and fill in the content section.

TemplateRouteWhat it shows
home/, /page/2…Home page: hero, rails, and latest episodes.
titles/movies, /series, /year/2024Paginated listing with sorting and year filtering.
title/movie/<slug>, /series/<slug>Detail page with player, seasons, and related titles.
season/series/<slug>/season/<n>A season with its episodes.
episode/series/<slug>/season/<n>/episode/<m>Episode with player and navigation.
genres, tags/genres, /tagsGenre and tag indexes.
term/genre/<slug>, /tag/<slug>Titles for a genre or a tag.
people, person/people, /person/<slug>Cast listing and a person's page.
search/search?q=Search results.
page/p/<slug>Static page. If the page picks template x and pages/x.tpl exists, that one is used.
mylist/my-list"My List" and "Continue Watching" (rendered in the browser).
offline/offlineThe page the PWA shows when there's no connection.
errors/<code>—Errors. errors/404 is looked up first, then errors/error.

A plugin can replace any template with the template_path filter or add data with template_data; that's why your templates shouldn't assume variables the core doesn't guarantee.

Variables per template #

Every template receives $site, $seo, and $template (the template's name). layout.tpl also sees every variable from the child template.

$site (the site's configuration):

KeyContents
name, tagline, descriptionSite name, tagline, and description.
footer_text, social_linksFooter text and the list of social links.
footer_pagesPages marked for the footer (each with title and url).
urlBase URL without a trailing /.
lang, langs, localeCurrent language, active languages, and locale (es_ES).
appearanceAppearance settings: primary, secondary, logo_media_id, favicon_media_id, custom_css…

$seo is a PageSeo object: {!! $seo->render() !!} prints the <title>, meta tags, hreflang, and JSON-LD. It goes once, inside <head>.

TemplateVariables
home$hero (featured titles), $rails (rows: each with its title and its titles), $latest_episodes, $series_by_id (each episode's series, by id), $genres, $titles, $pagination, $page
titles$heading, $type (movie, series, or null for years), $titles, $pagination, $page, $sort, $sorts, $base (path for pagination), $years
title$title, $sources (sources grouped for player()), $seasons, $episodes, $current_season, $related, $first_episode (series: the first episode of the first season; movies: null), $upcoming (true if there are no sources yet and the title is marked as "coming soon")
seasonSame as title, plus $season
episode$title, $season, $episode, $episodes, $seasons, $sources, $nav (prev and next)
genres, tags$terms
term$term, $titles, $pagination, $page, $sort, $sorts, $base, $siblings (other popular terms)
people$people, $pagination, $page
person$person, $titles, $credits, $collaborators, $pagination, $page
search$q, $titles, $people, $pagination, $page
page and pages/*$page (the page: title, content, template…)
mylist, offlineOnly the common ones
errors/*$status, $message

Each title's, episode's, term's, and person's fields are whatever the repositories return; they're listed in the PHP API. The most commonly used in a card: $t['title'], $t['url'], $t['type'], $t['year'], $t['rating'], $t['poster'], $t['backdrop'], $t['runtime_label'], and $t['seasons_count'].

To inspect what's available, turn on app.debug and temporarily write in the template:

html
<pre>@json(array_keys(get_defined_vars()))</pre>

Template helpers #

Functions meant to be used inside .tpl files. The ones that return HTML are printed with {!! !!}.

HelperReturns
img(?array $media, $size = 'thumb', array $opts = [])A <picture> with AVIF/WebP, srcset, width, and height. $size is the image type (poster, backdrop, still, profile, logo…) or a width. Options: alt, priority, lazy, sizes, class, max (max width for the srcset). Without an image it returns a .ph placeholder with the correct aspect ratio.
art_img(?array $wide, ?array $tall, $alt = '', $priority = false, $class = 'bg')An art-directed image: the poster on mobile and the backdrop from 768 px up. For billboards.
player(array $grouped, ?array $backdrop, string $label, string $beacon = '', bool $priority = false, string $actions = '', bool $upcoming = false)The full player: a facade with the image, a language/server bar, and the iframe or <video> on click. $beacon is the URL that logs the view (url('/api/view/' . $t['id'])).
trailer_facade(array $title)The YouTube trailer as a facade (doesn't load YouTube until clicked). '' if there's no trailer.
rating_badge($rating)The rating with its styling.
rank_svg(int $n)The Top 10's large, outlined number (1–10), as SVG.
wordmark(string $text, $height = 24, array $opts = [])The site name drawn in SVG, in uppercase and two tones, with no web fonts. Options: accent, split, id, use, class, tracking. Returns '' if the text has characters it can't draw: plan for a fallback text.
pagination(array $p, string $base, string $pattern = '%s/page/%d')Accessible pagination built from $pagination and $base.
lang_switcher(array $alternates = [], ?string $current = null)Language switcher.
theme_asset(string $file)URL of a file in assets/ with ?v= (the newest file's date). Looks in the child first, then the parent.
inline_css(string $file)The minified content of a CSS file in assets/, to drop into <style>.
child_theme_asset('css'|'js')The child theme's extra CSS or child.js URL; '' if there isn't one or if it's over budget.
theme_vars(array $appearance):root{--primary;--secondary;--on-primary} with the Appearance colors.
theme_setting(string $key, $default = null)An Appearance setting (appearance.<key>).
brand_asset(string $file)A MovieMaster brand file (assets/brand/).
compact_number(int $n)1500 → 1.5K, 2000000 → 2M.
media()The media repository: media()->find($id), media()->url($media, 480, 'jpg').
url(), lang_url(), current_lang(), setting(), plugin_active(), __(), _n(), e()The usual global functions.

And a partial worth reusing:

html
@include('partials/grid', ['titles' => $titles, 'lcp' => 2])

lcp is how many cards load with priority (true equals 2). Only set it for the ones visible without scrolling on a phone.

Images #

Always use img() or art_img(). They generate the modern formats, sizes, and dimensions that prevent layout shifts.

  • Only one priority image per view: the LCP one (the hero, the detail page's poster). Everything else, lazy (which is what img() does by default).
  • Match sizes to the actual on-screen width and cap small cards with max: fewer bytes on mobile.
  • Artwork for slides other than the first goes inside <template class="bb-art">. main.js turns it into an image once that slide is reached.
html
<a class="card" href="{{ $t['url'] }}">
  {!! img($t['poster'], 'poster', ['alt' => $t['title'], 'sizes' => '(max-width: 767px) 42vw, 200px', 'max' => 500]) !!}
  <p class="card-title">{{ $t['title'] }}</p>
</a>

Hooks every theme must fire #

Plugins hook into these points. If your layout.tpl doesn't fire them, plugins that depend on them won't show up (accounts, comments, ads, analytics…).

HookWhere
@hook('head')At the end of <head>, after the CSS.
@hook('body_open')Right after <body>.
@hook('nav_items')Inside the main menu. This is where the accounts plugin's "Log in" link lands.
@hook('before_content')Before the main content.
@hook('after_content')After the main content. This is where the comment box lands.
@hook('footer')Inside the footer.
@hook('body_close')Right before </body>, after the theme's scripts. This is where the core prints the ad scripts' "Code before &lt;/body&gt;"; if you don't fire it, that code lands in footer instead.
@hook('player_before'), @hook('player_after')Before and after player() in title.tpl and episode.tpl.

The body_class filter is also applied to the <body> class. The minimal skeleton for a layout.tpl:

html
@php $ap = $site['appearance'] ?? []; @endphp<!DOCTYPE html>
<html lang="{{ $site['lang'] }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
{!! $seo->render() !!}
<style>{!! inline_css('critical.css') !!}{!! child_theme_asset('css') !!}{{ theme_vars($ap) }}{!! str_replace('</style', '', (string) ($ap['custom_css'] ?? '')) !!}</style>
@hook('head')
</head>
<body class="{{ apply_filters('body_class', 'tpl-' . $template) }}">
@hook('body_open')
<header class="top">
  <a class="brand" href="{{ url('/') }}">{{ $site['name'] }}</a>
  <nav aria-label="{{ __('theme.main_nav') }}">
    <a href="{{ url('/movies') }}">{{ __('common.movies') }}</a>
    <a href="{{ url('/series') }}">{{ __('common.series') }}</a>
    @hook('nav_items')
  </nav>
</header>
@hook('before_content')
<main id="main">
  @yield('content')
</main>
@hook('after_content')
<footer>
  @hook('footer')
</footer>
<script type="module" src="{{ theme_asset('main.js') }}"></script>
@hook('body_close')
</body>
</html>

The full list of actions and filters, with their arguments, is in the hooks reference.

Critical CSS and budgets #

MovieMaster targets a 100 on Lighthouse, and the theme is what weighs the most on that score. The rules:

  • All CSS is inlined in a <style> in <head> via inline_css('critical.css'). There are no external stylesheets blocking render.
  • No web fonts. Use the system stack (system-ui, -apple-system, "Segoe UI", Roboto, sans-serif). For the text logo, use wordmark().
  • Budget: 20 KB of inlined CSS (minified) and 5 KB of initial JavaScript (main.js).

Budgets are declared in theme.json:

json
"budget": { "inline_css": 20480, "js_initial": 5120 }

A full theme can raise inline_css up to 32768 bytes if it needs to. In a child theme, the effective limit is the lowest of the core's, the child's, and the parent's, and it counts the sum of the base (the child's critical.css, or the parent's if it doesn't have one) plus the extra.

CSS and JavaScript for a child theme #

A child has two ways to add styles:

  1. assets/critical.extra.css: added after the parent's CSS. The normal choice for tweaks.
  2. Its own assets/critical.css: completely replaces the parent's. This is what Nébula and Lumen do, compiling it from src/theme.css.

For JavaScript, assets/child.js loads as a module after the parent's main.js. Cinema's layout.tpl already includes it:

html
@php $childJs = child_theme_asset('js'); @endphp
@if($childJs !== '')<script type="module" src="{{ $childJs }}"></script>
@endif

CSS variables #

Define your colors as variables in :root. theme_vars() adds --primary, --secondary, and --on-primary afterward with the colors the admin picks in Appearance, so your CSS should use var(--primary) instead of a hardcoded color.

The accounts and comments plugins render using these variables and the theme's classes; if they're missing, they fall back to neutral values:

  • Variables: --bg --bg-2 --bg-3 --fg --fg-2 --fg-3 --line --link --primary --on-primary --pad --r.
  • Classes: .wrap, .sec, .h1, .h2, .btn, .btn-primary, .btn-soft.

The card shared on social networks also reads --bg, --primary, and --link from your CSS's first :root, written in hex (#0b1020, not rgb() or another variable).

Theme JavaScript #

  • main.js is a module (<script type="module">) and the only initial script. It loads the rest on demand with import().
  • Import other modules with the same ?v= that main.js carries (import('./player.js?v=' + v)); otherwise the browser can mix old and new versions after an update.
  • For translated text in JavaScript, print it as JSON inside the page and read it from the script:
html
<script type="application/json" id="mm-i18n">@json(['all_results' => __('theme.suggest_all')])</script>
js
const t = JSON.parse(document.getElementById('mm-i18n')?.textContent || '{}');
  • Service worker (assets/sw.js, served at /sw): register it after the load event and never intercept /admin, /install, /api, or non-GET requests. Cinema registers it from main.js when the <script> has data-sw="{{ url('/sw') }}" (only if the PWA is enabled: setting('pwa.enabled', true)).

Contracts with plugins #

A contract is a markup promise: the theme leaves a slot with a specific shape, and plugins (or core scripts) rely on it. Declare the ones you fulfill in theme.json:

json
"contracts": ["player@1", "mylist@1", "install@1", "i18n@1", "account@1", "comments@1"]
ContractWhat the theme must have
player@1player()'s player inside #watch in episode.tpl (with #ep-page as the page's container), and the player_before/player_after hooks.
mylist@1#mm-this in detail pages, [data-mylist] to save, and #row-recent/#row-list where the lists are rendered. Details below.
install@1A [data-install] with a <button> inside, starting out hidden.
i18n@1<script type="application/json" id="mm-i18n"> with the text the scripts use.
account@1A link <a href="{{ url('/account/login') }}" rel="nofollow" data-account data-account-url="{{ url('/account') }}" data-in="My account">Log in</a> wherever you want. The plugin's script changes it to "My account" when there's a session. Wrap it in @if(plugin_active('members')).
comments@1@hook('comments') in title.tpl and episode.tpl, wherever you want the comment box.

Without account@1 or comments@1, the plugins place themselves: the "Log in" link via nav_items and the comment box via after_content. Contracts let you decide the exact spot.

Player, My List, and Continue Watching #

If you inherit from Cinema and keep its markup, all of this works without touching anything. If you write a full theme or change these pieces, this is the markup player.js and lists.js expect.

My List and Continue Watching #

These are saved in the visitor's browser (localStorage), with no accounts.

html
{{-- In title.tpl and episode.tpl: data for what's being watched --}}
<div id="mm-this" hidden
     data-u="{{ $title['url'] }}"
     data-t="{{ $title['title'] }}"
     data-i="{{ $title['backdrop'] ? media()->url($title['backdrop'], 480, 'jpg') : '' }}"
     data-m="{{ $title['year'] }}"></div>

{{-- Save button --}}
<button type="button" data-mylist aria-pressed="false"
        data-on="✓ {{ __('theme.in_list') }}" data-off="+ {{ __('theme.my_list') }}">+ {{ __('theme.my_list') }}</button>

{{-- Series: "Play" becomes "Continue S01E02" if an episode has been watched --}}
@if($title['type'] === 'series' && $first_episode)
  <a class="btn" href="{{ url('/series/' . $title['slug'] . '/season/' . $first_episode['season_number'] . '/episode/' . $first_episode['episode_number']) }}"
     data-resume="{{ __('theme.resume') }}"><span>{{ __('theme.play') }}</span></a>
@endif
  • In home.tpl and mylist.tpl, #row-recent and #row-list receive the cards. data-grid renders them as a grid instead of a rail. #mm-empty is hidden if there's anything to show.
  • Episode links a.ep get the seen class once the visitor has watched them.

Player #

player() generates all the markup. What the theme must respect:

  • The container: .facade inside .player. In episode.tpl, #ep-page > #watch > .player; that way a hot episode switch only replaces that part.
  • Next episode: an a[data-next] with data-name and data-img. .player carries data-credits (seconds before the end) and data-wait (countdown) from Settings → Player.
  • Skip intro: with active segments, .facade carries data-seg and player.js adds a button.btn.sk for the duration of the intro. The text comes from #mm-i18n (skip_intro, skip_recap).
  • Full screen on iPhone: the player gets .is-fs. Rules that constrain its size go under .player:not(.is-fs).
  • Classes the script adds that you can style: .dd-m, .dd-o (dropdowns), .nx (next-up card), and .sk (skip).

A third-party iframe player can talk to MovieMaster with parent.postMessage: 'mm:credits' (show the next-up card now), 'mm:next' (advance to the next episode), 'mm:ended' (it finished), and, optionally, its progress {currentTime, duration}.

Home page and rails #

Cinema's main.js expects [data-nav-toggle] (mobile menu button), [data-rail] (scrollable rails), and [data-hero] (carousel). The Top 10 rail is .rail.top and each card is .t10, with the number from rank_svg() (colored via .t10 svg path).

SEO and accessibility #

The core generates the SEO; the theme just needs not to break it:

  • {!! $seo->render() !!} once in <head> and <html lang="{{ $site['lang'] }}">.
  • A single <h1> per page. Card titles go in <p> or <span>, not <h2>/<h3>, so they don't inflate the heading structure.
  • Alt text on images with content (alt in img()); alt="" on decorative ones.
  • Enough contrast and visible focus on anything clickable. Icons without text get aria-label.
  • The footer's brand is the site's own (its logo or its name), never MovieMaster's "M".

Check and publish #

bash
php bin/console.php theme:check my-theme
php bin/console.php cache:clear

theme:check compiles and checks the syntax of every template, validates theme.json, checks the parent and the budgets, and looks for files that shouldn't be in an extension (.env, keys, databases, .git…). Common errors:

MessageFix
screenshot.png missing (required in spec 1)Add the screenshot (880×660, under 300 KB).
parent theme 'x' not foundInstall the parent or fix parent.
inline CSS over budget: … > 20480Trim the CSS or, in a full theme, raise budget.inline_css (max 32768).
… is only loaded for child themescritical.extra.css/child.js on a theme with no parent: move its content into your main files.
templates/x.tpl: …Syntax error in a template: the line number given is from the compiled PHP.

Before publishing, go through this checklist:

  • [ ] theme:check with no errors and cache:clear done.
  • [ ] Lighthouse 100 on mobile for the home page, detail page, and episode.
  • [ ] Every layout hook, and, if you change the markup, the contracts you declare.
  • [ ] Only one priority image per view.
  • [ ] Tested with long names, titles with no image and no translation, and both languages.
  • [ ] Your own screenshot, with no third-party artwork (real movie posters, brand logos).

Packaging (ext:pack) and publishing to the store are explained in Packaging and publishing.

Known pitfalls #

  • Spaces before : and minification. minify_css removes the spaces around :, so parent :is(child) (or parent :hover, parent :first-child) becomes parent:is(child), which means something else. Write parent *:is(child).
  • content-visibility: auto isolates CSS counters. If you number with counter(), each block starts over. The Top 10 numbers come from the template (rank_svg($loop->iteration)).
  • Screen-reader-only text inside a horizontally scrolling rail. An .sr with position:absolute needs a positioned ancestor; otherwise it widens the page.
  • More priority images isn't better. Every extra priority competes with the LCP one and makes it worse.
  • Content outside @section in a child template is silently discarded. See templates.
  • Changes that don't show up. Compiled templates refresh themselves when the .tpl changes, but the page cache doesn't. After touching the theme in production, run cache:clear (activating or updating the theme already clears it).
  • Full-page screenshots taken with automated tools don't load lazy images: that's not a theme bug.

¿Te quedó alguna duda?

Escríbenos y te ayudamos con tu caso.

Hablar con nosotros
¿Hablamos?