Reputation: 13
I am new to Drupal 8 my question is: is there a way to create a php function in .theme file and calling it from a twig template file?
Upvotes: 0
Views: 66
Reputation: 156
One way is to use global preprocess in .theme file.
function MYTHEME_preprocess(array &$variables, $hook) {
//this is a global hook, its variables are available in any template file
$variables['test'] = 'today';
}
{{ test }}
will render 'today'.
Another way is create own custom Twig functions in a custom module. Reference -https://drupal.stackexchange.com/questions/271770/how-to-call-a-function-in-a-twig-file
Can call like this on twig templates {{ getRoleValues('admin') }}
src/MyTwigExtension.php
<?php
namespace Drupal\MyTwigModule;
/**
* Class DefaultService.
*
* @package Drupal\MyTwigModule
*/
class MyTwigExtension extends \Twig_Extension {
/**
* {@inheritdoc}
* This function must return the name of the extension. It must be unique.
*/
public function getName() {
return 'role_values';
}
/**
* In this function we can declare the extension function
*/
public function getFunctions() {
return array(
new \Twig_SimpleFunction('getRoleValues',
[$this, 'getRoleValues'],
['is_safe' => ['html']]
)),
}
/**
* Twig extension function.
*/
public function getRoleValues($roles) {
$value = 'not-verified';
if ($roles == "admin") {
$value = 'verified';
}
return $value;
}
}
src/MyTwigModule.services.yml
services:
MyTwigModule.twig.MyTwigExtension:
class: Drupal\MyTwigModule\MyTwigExtension
tags:
- { name: twig.extension }
Upvotes: 1