如何将内联 PHP 添加到 .twig 文件?
How to add inline PHP to a .twig file?
我正在尝试修改 .twig 文件中的 <body>
标签。
正文标签看起来像这样...
<body{{ body_id is not empty ? ' id=' ~ body_id }} >
...我想添加...
class="<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>-page"
但是当我这样做的时候,我会遇到这样一团糟:
<body id="foo" class="<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>-page">
简而言之,如何将内联 PHP 添加到 .twig 文件?
Twig 不会解释 PHP - 它不明白它的意思。
更好的方法是将 basename($_SERVER['PHP_SELF'], '.php'
的结果从您调用模板的任何 PHP 脚本传递到 twig 上下文中。
假设您调用上下文变量 body_classes
然后您可以将模板更新为如下内容:
<body{{ body_id is not empty ? ' id=' ~ body_id }}{{ body_classes is not empty ? ' class=' ~ body_classes }} >
编辑:虽然这种方法乍一看似乎有悖常理,但它为您提供了分离逻辑和表示的好处。
我正在尝试修改 .twig 文件中的 <body>
标签。
正文标签看起来像这样...
<body{{ body_id is not empty ? ' id=' ~ body_id }} >
...我想添加...
class="<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>-page"
但是当我这样做的时候,我会遇到这样一团糟:
<body id="foo" class="<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>-page">
简而言之,如何将内联 PHP 添加到 .twig 文件?
Twig 不会解释 PHP - 它不明白它的意思。
更好的方法是将 basename($_SERVER['PHP_SELF'], '.php'
的结果从您调用模板的任何 PHP 脚本传递到 twig 上下文中。
假设您调用上下文变量 body_classes
然后您可以将模板更新为如下内容:
<body{{ body_id is not empty ? ' id=' ~ body_id }}{{ body_classes is not empty ? ' class=' ~ body_classes }} >
编辑:虽然这种方法乍一看似乎有悖常理,但它为您提供了分离逻辑和表示的好处。