如何在树枝中嵌入 php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20296850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:02:49  来源:igfitidea点击:

How to embed php in twig

phpsymfonytwig

提问by user3051319

I have a do_shortcut and I need to embed it in a twig template. I tried by coping the code in a php file my-code.php:

我有一个 do_shortcut,我需要将它嵌入到树枝模板中。我尝试通过处理 php 文件 my-code.php 中的代码:

<?php do_shortcut('[my-code]'); ?>

Next, in the twig page over.twig:

接下来,在 twig 页面 over.twig 中:

   {{ include ('options/my-code.php') }}

/* I also tried */

   {% php %}
            <?php do_shortcut('[my-code]'); ?>
   {% endphp %}

But doesn't work. Any suggestion? Thanks.

但不起作用。有什么建议吗?谢谢。

回答by Wouter J

You can't do that, you should create a twig extension and transform the php function into a twig function: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

你不能这样做,你应该创建一个树枝扩展并将php函数转换为树枝函数:http: //symfony.com/doc/current/cookbook/templating/twig_extension.html

回答by StLia

About the includepart, create a my_code.html.twigfile at app/Resources/views/my_code.html.twig and copy-paste your code from my-code.php

关于这include部分,my_code.html.twig在 app/Resources/views/my_code.html.twig创建一个文件,然后复制粘贴你的代码my-code.php

Then you can include that code anywhere like :

然后您可以在任何地方包含该代码,例如:

{% include 'my_code.html.twig' %}

EDIT: tested and working in symfony3

编辑:在 symfony3 中测试和工作

回答by KMK

Try this code:

试试这个代码:

{{ wp.do_shortcode('[shortcode]')|raw }}