6

We have a website that is built on top of Symfony framework and I have been given a task of allowing the admins to make changes to the email templates or even the twig templates via admin panel like in WordPress where you go to the editor and make changes to the files.

I know Symfony is not a CMS and I am wondering if allowing admins to edit email templates and other twig templates is at all possible to do. The templates are not saved in database they are in their normal location NameBundle/Resources/views and as we know on production Symfony uses cache.

While searching online I came across Ace editor and CodeMirror but again I am stuck at how to use anything like this with Symfony

I will really appreciate if anyone can push me in right direction.

1
  • Since twig templates are plain files, you could always write a code that will file_get_contents(), then modify, and then put it back in using file_put_contents() or similar file read/write functions.
    – Muhammed
    Commented Mar 1, 2016 at 5:56

2 Answers 2

7

I had the same need recently.

I chose to put the edited content in a app/Resources/AcmeBundle/views/Include/menu.html.twig file because I didn't want to put this in a Bundle. A file src/AcmeBundle/Resources/views/Include/menu.html.twig is loaded the first time this page is loaded, its content will be used as a basis for the editable Twig template. The file can also be empty.

Controller's function:

 /**
 * @Route(
 *      "/edit/menu",
 *      name = "page_edit_menu"
 * )
 */
public function editMenuAction(Request $request)
{
    $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Access denied.');

    // Output file.
    $filepath = $this->container->getParameter('kernel.root_dir').
        '/Resources/AcmeBundle/views/Include/menu.html.twig';

    // Dummy object used in the form.
    $file = new \ArrayObject();

    // Check that the output file exists.
    if (file_exists($filepath)) {
        // Load the file content.
        $file->content = file_get_contents($filepath);
    } else {
        // The file is missing, load the file located in the Bundle instead.
        $file->content = file_get_contents(
            $this->container->get('kernel')->locateResource(
            '@AcmeBundle/Resources/views/Include/menu.html.twig')
        );
    }

    // Declare the form.
    $form = $this->createFormBuilder($file)
        // A textarea for the file content.
        ->add('content', 'textarea', array(
            'attr' => array(
                'rows' => 16,
            )
        ))
        ->add('submit', 'submit', array(
            'label' => 'Save'
        ))
        ->getForm();

    $form->handleRequest($request);

    if ($form->isValid())
    {
        // Save the file in app/Resources/...
        file_put_contents($filepath, $file->content);

        // Clear cache (otherwise the changes won't be applied)
        // Be patient, it can take about 15 seconds.
        $console = 'php '.$this->container->getParameter('kernel.root_dir').
            '/console';

        exec($console.' cache:clear --env=prod');
        exec($console.' cache:warmup --env=prod');

        $this->get('session')->getFlashBag()->add('notice',
            'Content saved succesfully.');

        return $this->redirect($this->generateUrl('page_edit_menu'));
    }

    return $this->render('editMenu.html.twig', array(
        'form' => $form->createView(),
    );
}

Twig file

The associated Twig file editMenu.html.twig only contain the form:

{{ form(form) }}

Usage

Here is how the editable template is used where you want to display the file previously edited:

{% include('AcmeBundle:Include:menu.html.twig') %}

Thanks to templates overriding, the app/Resources/AcmeBundle/views/Include/menu.html.twig file will be used instead of the one in the Bundle.

Git

If you use git, you have to add the file path in the .gitignore file:

# File that can be edited from the admin:
/app/Resources/AcmeBundle/views/Include/menu.html.twig

Without this, an update with git may alter or delete this file.

HTML editor

If you want a WYSIWYG editor, you can install TinymceBundle which provide an HTML editor. Here is a quick guide to use it if you already have jQuery. Otherwise follow the documentation.

composer require "stfalcon/tinymce-bundle:dev-master"

A simple configuration to add to app/config/config.yml:

stfalcon_tinymce:
    selector: ".tinymce"
    language: %locale%
    theme:
        simple:
            theme: "modern"
            plugins: "link"
            toolbar1: "undo redo | bold italic | bullist numlist outdent indent | link"

And add 'class' => 'tinymce', after 'rows' => 16, and {{ tinymce_init() }} in your Javascript.

13
  • This is so kind of you to share, I will go through these and get back to you
    – Saadia
    Commented Mar 1, 2016 at 11:26
  • Can you please explain to me the section of Twig file and Usage, my understanding is that inside app/Resources/AcmeBundle/views/Include/menu.html.twig I only need to have the {{ form(form) }} but then where do i put {% include('AcmeBundle:Include:menu.html.twig') %}
    – Saadia
    Commented Mar 1, 2016 at 11:30
  • 1
    Just be aware that clearing the cache on your production server whenever you update a template can cause unpleasant surprises for your users. Also be aware that updating files under Resources can have source code control issues. Be a shame to lose all your changes the next time composer update is run.
    – Cerad
    Commented Mar 1, 2016 at 13:53
  • 1
    @A.L - The basic problem is that you do need to refresh the cache whenever a template file is updated in order for the changes to be seen. I have never tried to implement this sort of solution. If faced with a similar task I would look at some of the existing cms solutions and see what they do. I would definitely store changed template files in a dedicated directory (or a database). And then figure how to update just the twig cache.
    – Cerad
    Commented Mar 1, 2016 at 14:31
  • 1
    @A.L - All good questions to which I don't know the answer. Twig 'compiles' the templates into php. You can look in the cache directory to get an idea of the results. I'm fairly confident you can have twig compile a single template but I'd have to research to determine the details. Hence the notion of seeing how other people do it.
    – Cerad
    Commented Mar 1, 2016 at 15:26
4

Twig lets you use multiple template loaders where you can have templates stored as string instead of files. One of the examples shows probably exactly what you need. They're using strings as templates.

I think this feature has changed recently because I remember there used to be Twig_Loader_String class. It looks like it's been removed since 1.15.

In your case you store templates in the database and then add them to the filter chain just like here: http://twig.sensiolabs.org/doc/api.html#twig-loader-chain

Symfony configuration has also twig.loader tag for adding new loaders.

3
  • Two Martins... it's taken a while on here, but now StackOverflow has confused me. hah
    – Martin
    Commented Mar 1, 2016 at 8:27
  • @Martin(s) :) many thanks for that, I will have a look into these resources, any idea how to display these in web editor and update them when saved via admin panel?
    – Saadia
    Commented Mar 1, 2016 at 10:08
  • I don't use Wordpress so I don't know. Anyway, editing and storing temples is unrelated to Twig. You can do it in any way you want.
    – martin
    Commented Mar 1, 2016 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.