Display content from a row / database and create links with a twig

For several reasons, including content translation, I had to create a simple CMS to display the pages of my Symfony2 application.

Now my problem is that the seams cannot display content from a string. Twig only accepts files. My content may contain dynamic parts such as locale or similar, so rendering the branch power will be very useful.

I tried to display it using a TwibstringBundle , but its functionality is quite limited and does not work with the path function.

Any suggestions to solve the problem?

+4
source share
3 answers

see http://twig.sensiolabs.org/doc/functions/template_from_string.html and http://symfony.com/doc/current/cookbook/templating/twig_extension.html#register-an-extension-as-a- service

{% include template_from_string("Hello {{ name }}") %} {% include template_from_string(page.template) %} 

Since the line loader is not loaded by default, you need to add it to your configuration.

 # src/Acme/DemoBundle/Resources/config/services.yml acme.twig.extension.loader: class: Twig_Extension_StringLoader tags: - { name: 'twig.extension' } 

Where Acme / acme is your application name and DemoBundle is the package for which you want to enable it.

+15
source

Symfony 2.7 makes PHP easy:

  $twig = $this->get('twig'); $template = twig_template_from_string($twig, 'Hello, {{ name }}'); $output = $template->render(['name' => 'Bob'])); 
+3
source

twig_template_from_string The source code of the function is as follows:

 function twig_template_from_string(Twig_Environment $env, $template) { return $env->createTemplate($template); } 

This means that if you already have a twig environment , then it is better to call directly:

 $template = $env->createTemplate($templateString); $parsedContent = $template->render(array('a'=>'b')); 
+2
source

Source: https://habr.com/ru/post/1402630/


All Articles