创建一个 php 函数来添加新节点
Create a php function to add new node
我是 Drupal 8 的新手,我的问题是:
有没有办法在 .theme 文件中创建一个 php 函数并从 twig 模板文件中调用它?
一种方法是在 .theme 文件中使用全局预处理。
function MYTHEME_preprocess(array &$variables, $hook) {
//this is a global hook, its variables are available in any template file
$variables['test'] = 'today';
}
{{ test }}
将呈现 'today'.
另一种方法是在自定义模块中创建自己的自定义 Twig 函数。
参考-https://drupal.stackexchange.com/questions/271770/how-to-call-a-function-in-a-twig-file
可以在 twig 模板上这样调用 {{ 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 }
我是 Drupal 8 的新手,我的问题是: 有没有办法在 .theme 文件中创建一个 php 函数并从 twig 模板文件中调用它?
一种方法是在 .theme 文件中使用全局预处理。
function MYTHEME_preprocess(array &$variables, $hook) {
//this is a global hook, its variables are available in any template file
$variables['test'] = 'today';
}
{{ test }}
将呈现 'today'.
另一种方法是在自定义模块中创建自己的自定义 Twig 函数。 参考-https://drupal.stackexchange.com/questions/271770/how-to-call-a-function-in-a-twig-file
可以在 twig 模板上这样调用 {{ 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 }