- Call PHP function from Twig template
- Solution 2
- Solution 3
- Solution 4
- Solution 5
- Reynier
- Comments
- Php function inside twig template
- How to call a php template from a twig template
- Php function inside twig template
- Twig: Update template data from ajax call
- Call Helper functions inside Twig (Timber)
- [symfony] Call PHP function from Twig template
- The answer is
Call PHP function from Twig template
Its not possible to access any PHP function inside Twig directly.
What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.
Solution 2
There is already a Twig extension that lets you call PHP functions form your Twig templates like:
Hi, I am unique: >. And > is floor of 7.7.
Solution 3
I am surprised the code answer is not posted already, it’s a one liner.
$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));
$this->twig->addFilter(new \Twig\TwigFilter('getVariations','getVariations'));
Twig 3 but as function instead of a filter:
$this->twig->addFunction(new \Twig\TwigFunction('getVariantsFunc', 'getVariations'));
Solution 4
You can check your all defined function by
$arr = get_defined_functions(); print_r($arr);
this will give you array of all functions in if your function exist in it you can use it like:
Solution 5
I know this is an old thread. But with symfony 3.3 I did this:
Reynier
Comments
I have a function in my controller that returns array of entities so in my twig template I do this to iterate over elements:
private function DetailCombination($arr, $level, &$result, $curr = array()) < for ($i = 0; $i < count($arr); $i++) < $new = array_merge($curr, array($arr[$i])); if ($level == 1) < sort($new); if (!in_array($new, $result)) < $result[] = $new; >> else < combinations($arr, $level - 1, $result, $new); >> >
for ($i = 0; $i < count($arr); $i++) < $this->DetailCombination($arr, $i + 1, $result); > // TEST foreach ($result as $arr) < echo join(" ", $arr) . '
'; >
It’s possible access to the PHP function from Twig template in order to get all the possible combinations of elements in entity? How? ** UPDATE ** This is the function that returns entities processed after by Twig Template:
private function getVariations($category_id) < $items = array(); $em = $this->getDoctrine()->getManager(); $entityCategory = $em->getRepository('CategoryBundle:Category')->find($category_id); foreach ($entityCategory->getProductDetails() as $entity) < if ($entity->getToProduct() == 1) < foreach ($entity->getDetailGroup() as $group) < if (!array_key_exists($group->getName(), $items)) < $items [$group->getName()] = array(); > $items [$group->getName()] [] = $entity; > > > return $items; >
Php function inside twig template
Rendering both directly from the controller works, but when I want to render de php template inside the Twig template using the but then Symfony uses Twig to parse the template, not the PHP template engine. The extension could provide function which will take PHP template name as an argument and will render it.
How to call a php template from a twig template
I have two template files. One is a twig template and another is a php template file. Rendering both directly from the controller works, but when I want to render de php template inside the Twig template using the but then Symfony uses Twig to parse the template, not the PHP template engine.
How do I tell Twig to render the template file as a php template instead of a Twig template?
You’ll have to write an extension for Twig. The extension could provide function which will take PHP template name as an argument and will render it. Why are you using two different templating engines?
Symfony — Call PHP function from Twig template, Its not possible to access any PHP function inside Twig directly. What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too. Usage example$this->twig->addFunction(new \Twig\TwigFunction(‘getVariantsFunc’, ‘getVariations’));Feedback
Php function inside twig template
I have a twig template in which i render some information taking from the database. The length of the information is quite large and it does not fit in the space provided for it. I want to use substr function of php inside my twig template.
The index.html.twig contains
The description is very long I want to display the first 80 characters of the whole description.
substr(patent.description,0,80)
Can anyone guide me how i can use this function inside my twig template?
The slice function does this,
The slice filter works as the array_slice php function for arrays and substr for strings. It was added in Twig 1.6.
Symfony — Use PHP function in TWIG?, In a twig template: << explode(",", "It's raining, cats and dogs.").0 | raw >> this will output «It’s raining». By default, returned values are escaped in Twig. Twig_SimpleFunction is the preferred class to use. All other function related classes in Twig are deprecated since 1.12 (to be removed in 2.0). In a …<>
Twig: Update template data from ajax call
In the ‘index.html’ the default action is list all users. When I change the filter, this call a ajax function in ‘user.js’.
$.ajax(< url: 'user/find/'+params, type: 'get', data: null, async: false, dataType: 'html', success: function(dataJson)< . >, error: function(jqXHR, textStatus, errorThrown)<>, complete: function( jqXHR, textStatus )<> >); return jsonContratos; >
This ajax function call the class User.php
class User extends AppRequest < public function __construct()<>public function index_action() < $this->template('index.html', Array('users' => $this->find())); > public function find() < $arrayUsers = dataBase->findUsersByFilters($_GET['params']); if( $this->isAjaxRequest() ) < $array = Array('users' =>$arrayUsers) $this->template('index.html', $array); >else < return $arrayUsers; >> >
Questions: -How can I send the new users list to the template, using the ajax callback? -Or what the best way to do this? -Is possible to do this with Json?
As already mentioned, don’t use async: false . AJAX is — by definition — asynchronous. Concerning your question: simply update your view in the success callback. You return HTML so simply inject it:
$.ajax(< url: 'user/find/'+params, type: 'get', data: null, async: false, dataType: 'html', success: function(data, textStatus, jqXHR)< // for example $("#some-id-or-class-of-your-main-element").html(data); >, error: function(jqXHR, textStatus, errorThrown)<>, complete: function( jqXHR, textStatus )<> >);
How to call a php template from a twig template, I have two template files. One is a twig template and another is a php template file. Rendering both directly from the controller works, but when I want to render de php template inside the twig template using the <% include 'mytemplate.html.php' %>but then Symfony uses Twig to parse the template, …%>
Call Helper functions inside Twig (Timber)
Warning: call_user_func_array() expects parameter 1 to be a valid callback, class ‘ThemeHelpers’ not found in /var/www/html/wp-content/plugins/timber-library/lib/Twig.php on line 268.
Does anyone know how to call a method of a different class inside Twig?
As far as I know you can’t call php classes directly from your twig template. What you can do is setting up a Twig filter which communicates with your class and returns the needed value.
You would have this in your php controller file that is responsible to load your twig template:
function add_to_twig($twig) < /* this is where you can add your own fuctions to twig */ $twig->addExtension(new Twig_Extension_StringLoader()); $twig->addFilter('twg_get_template_name', new Twig_Filter_Function('twg_get_template_name')); return $twig; > add_filter('get_twig', 'add_to_twig');
In your Twig template you would call the filter like this:
Because it’s a filter function it expects a value «to filter», so pass at least an empty string.
If I were in that situation I probably would determine the name of the template in your controller and send the value to your Twig template directly instead of calling the php class via a filter-function.
I tried your approach — it works. But using a filter feels a little hacky, especially when no value is passed. Why not create a timber function the same way as a filter? Bridging own functions from plain php into twig is not great, but I also don’t see another solution to this.
After playing around a little, I came up with a different approach. I now fixed my need by customizing the Timber Object and adding a template property to the post variable.
Looks something like this:
class OnepagePost extends TimberPost < var $_template; // Add template property to Twig Object public function template() < return Helpers::get_template_name( $this->custom['_wp_page_template'] ); > >
Then inside the .php file where the Twig View gets called, I called the custom object like this:
$context['posts'] = new Timber\PostQuery( $args, 'OnepagePost' ); Timber::render('onepager.twig', $context);
Inside the Twig Template I’m able to get my custom property very easy (in my way the template):
You can call static functions from a Twig file in Timber using the array notation, where first item is the name of the class and the second item the name of the static method you want to call:
Passing PHP functions within TWIG templates, I’m trying to figure out a way that I can pass PHP code directly within the templates in TWIG without having to create separate extensions for each function. Basically a simple function that could parse out the PHP and run the code in the template.
[symfony] Call PHP function from Twig template
I have a function in my controller that returns array of entities so in my twig template I do this to iterate over elements:
In my controller I have also this PHP function:
private function DetailCombination($arr, $level, &$result, $curr = array()) < for ($i = 0; $i < count($arr); $i++) < $new = array_merge($curr, array($arr[$i])); if ($level == 1) < sort($new); if (!in_array($new, $result)) < $result[] = $new; >> else < combinations($arr, $level - 1, $result, $new); >> >
I can call it in this way:
for ($i = 0; $i < count($arr); $i++) < $this->DetailCombination($arr, $i + 1, $result); > // TEST foreach ($result as $arr) < echo join(" ", $arr) . '
'; >
It’s possible access to the PHP function from Twig template in order to get all the possible combinations of elements in entity? How?
This is the function that returns entities processed after by Twig Template:
private function getVariations($category_id) < $items = array(); $em = $this->getDoctrine()->getManager(); $entityCategory = $em->getRepository('CategoryBundle:Category')->find($category_id); foreach ($entityCategory->getProductDetails() as $entity) < if ($entity->getToProduct() == 1) < foreach ($entity->getDetailGroup() as $group) < if (!array_key_exists($group->getName(), $items)) < $items [$group->getName()] = array(); > $items [$group->getName()] [] = $entity; > > > return $items; >
This question is related to symfony twig symfony-2.3
The answer is
Its not possible to access any PHP function inside Twig directly.
What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.
There is already a Twig extension that lets you call PHP functions form your Twig templates like:
Hi, I am unique: >. And > is floor of 7.7.
You can check your all defined function by
$arr = get_defined_functions(); print_r($arr);
this will give you array of all functions in if your function exist in it you can use it like:
I am surprised the code answer is not posted already, it’s a one liner.
$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));
While I agree with the comments about passing in variables from your controller you can also register undefined functions when setting up the twig environment
$twig->registerUndefinedFunctionCallback(function ($name) < // security $allowed = false; switch ($name) < // example of calling a wordpress function case 'get_admin_page_title': $allowed = true; break; >if ($allowed && function_exists($name)) < return new Twig_Function_Function($name); >return false; >);
Haven’t tried calling a function on an object as the original question requested
$twig->getEnvironment()->addFilter( new \Twig_Filter('md5', function($arg)< return md5($arg); >) );
This creates a new filter named md5 which returns the MD5 checksum of the argument.
I know this is an old thread. But with symfony 3.3 I did this:
If you really know what you do and you don’t mind the evil ways, this is the only additional Twig extension you’ll ever need:
function evilEvalPhp($eval, $args = null)