MicWit
MicWit

Reputation: 685

How can I create a composer bundle with error templates in Symfony?

We have a bunch of webapps that will be created in Symfony. To make this easier, I have created a bundle for the template. So the main file (TemplateBundle.php) contains (with comments stripped out):

<?php
namespace company\TemplateBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class TemplateBundle extends Bundle
{
}

And then in Resources/views/template.html.twig is the main twig template, using codeblocks for things like title, content area etc.

In the app, all I do in the base.html.twig (that all other twig files extend) is:

{# app/Resources/views/base.html.twig #}

{% extends 'TemplateBundle::template.html.twig' %}

{% block title %}App Name{% endblock %}

{% block content %}
    <div class="container page-content">{% block body %}{% endblock %}</div>
{% endblock %}

{% block stylesheets %}
    <link rel="stylesheet" href="{{ asset('css/appspecific.css') }}">
{% endblock %}

and on deployment when the composer install is run, this bundle is installed and when the template is updated, all apps just update to the new version and get re-deployed. So far so good.

The place I ran into a problem is when I wanted to add the error pages to the bundle. So at the moment in the app, they are in /app/Resources/TwigBundle/views/Exception/errorxxx.html.twig for example error404.html.twig:

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

{% block body %}
    <h1>That Page Could Not Be Found</h1>
    <p>It seems that you are trying to access a page that doesn't exist. Please check your spelling and try again.</p>
{% endblock %}

This way the error pages extend base with the title etc set, which then extends the template with the main site template. So rather than have to add the error pages to each project (and update each project when the content of an error page changes), I want to add them to the bundle.

Is there an easy way of doing this (either in the template bundle or I can create another) in order to over ride the default twig error pages?

If there is no easy way, what other options are there?

Upvotes: 0

Views: 88

Answers (1)

MicWit
MicWit

Reputation: 685

So it seems the answer is to override the bundle with my bundle. To do this all I did was modify TemplateBundle.php to

<?php
namespace company\TemplateBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class TemplateBundle extends Bundle
{
    public function getParent()
    {
        return 'TwigBundle';
    }
}

Then, I can replace templates, controllers etc where required, so I just put my error templates (for example error404.html.twig) into the Resources/views/Exception directory (same as where they are located in the TwigBundle bundle in /vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle) and because they extend base.html.twig, they will now look like the rest of the application.

Upvotes: 0

Related Questions