Scott Keck-Warren
Scott Keck-Warren

Reputation: 1952

Require a Twig Block Be Defined in a Child

I have the <title> tag defined as a block in my base twig file and I want to make sure all my views override this block. Is there a way to mark the block as required so I get an error if I forget?

Upvotes: 2

Views: 201

Answers (1)

sjagr
sjagr

Reputation: 16512

This isn't built into Twig (maybe you should make a feature request!)

There is one way I can think of, but it's not completely using blocks.

If you have a base.html.twig of, let's say for a quick example:

<title>{% block title %}{{ title }}{% endblock %}</title>

and you extend this block:

{% extends '::base.html.twig' %}

but don't declare a {% block title %} - then Twig will throw a notice in the development environment (and in the prod.log in the Production environment) about an unset variable. (You really shouldn't want Symfony to throw an error in Production for something trivial like this.)

Then there's two ways of "satisfying the requirement":

  1. Pass a title variable into your extended Twig file
  2. Override the title block with your own contents

Example 1, in your controller:

return $this->render('AcmeBundle:Extended:view.html.twig', array(
    'title' => 'My fancy title'
));

Example 2, in your Twig file:

{% extends 'AcmeBundle::base.html.twig' %}

{% block title %}My fancy title{% endblock %}

Upvotes: 1

Related Questions