我可以将我的 php 代码传递给木材的树枝代码吗 [英] can i pass my php code to twig code of timber
问题描述
我想知道我是否可以将任何类型的PHP代码转换为twig,我想知道的是,例如我是否可以通过代码.
I would like to know if I can convert any types of PHP code to twig, what I want to know is, for example, whether I can pass the code.
<?php
if (ICL_LANGUAGE_CODE == 'in'):?
到
{{ lang.en }}
有没有办法添加任何PHP代码并将其变成树枝并识别它?
Is there a way to add any PHP code and turn it into a twig and recognize it?
我使用 WordPress 的 Timber 模板.
I use the Timber template for WordPress.
推荐答案
有一种传递函数的好方法(更准确地说,是将函数注册到 Twig).
There is a good way to pass your functions (more correctly, register the function to Twig).
过滤器钩子timber/twig
中有一个类可以帮助我们将函数传递给Twig.它调用 Timber\Twig_Function
.
There is a class in filter hook timber/twig
could help us pass functions to Twig. It calls Timber\Twig_Function
.
new Timber\Twig_Function(
'function_name_that_will_be_called_in_Twig',
'function_name_in_php'
);
// OR
new Timber\Twig_Function(
'function_name_that_will_be_called_in_Twig',
function( $input ) {
// anonymous function is ok too.
}
);
functions.php
add_filter( 'timber/twig', 'add_to_twig' );
function hello_in_php( $name = 'world' ) {
$hello = 'Hello ';
$hello .= $name;
return $hello;
}
function add_to_twig( $twig ) {
$func = new Timber\Twig_Function('hello', 'hello_in_php');
$filter = new Timber\Twig_Function('introduce', function( $name ) {
return "I'm ${name}!";
});
$twig->addFunction($func); //Registering a pre-defined function
$twig->addFunction($filter); //Registering a filter function
return $twig;
}
index.twig:
<p id='a'>{{ hello() }}</p>
<p id='b'>{{ hello('who?') }}</p>
<p id='c'>{{ "Batman"|introduce }}</p>
结果是:
<p id='a'>Hello World</p>
<p id='b'>Hello who?</p>
<p id='c'>I'm Batman!</p>
来源:https://timber.github.io/docs/guides/extending-timber/#adding-functionity-to-twig
这篇关于我可以将我的 php 代码传递给木材的树枝代码吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!