简体   繁体   English

如何将内联 PHP 添加到 .twig 文件中?

[英]How to add inline PHP to a .twig file?

I am trying to modify the <body> tag in a .twig file.我正在尝试修改 .twig 文件中的<body>标签。

The body tag looks like this...身体标签看起来像这样......

<body{{ body_id is not empty ? ' id=' ~ body_id }} >

...and I want to add... ......我想补充......

class="<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>-page"

But when I do so I end up with this mess:但是当我这样做时,我最终会陷入困境:

<body id="foo" class="<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>-page">

In short, how can I add inline PHP to a .twig file?简而言之,如何将内联 PHP 添加到 .twig 文件中?

Twig won't interpret PHP - it doesn't understand what it means. Twig 不会解释 PHP - 它不明白它的意思。

A better way of doing this is to pass the result of basename($_SERVER['PHP_SELF'], '.php' into the twig context from whatever PHP script you call the template.一个更好的方法是将basename($_SERVER['PHP_SELF'], '.php'的结果从您调用模板的任何 PHP 脚本传递到树枝上下文中。

Assuming you call the context var body_classes you can then update the template to something like this:假设您调用上下文 var body_classes您可以将模板更新为如下所示:

<body{{ body_id is not empty ? ' id=' ~ body_id }}{{ body_classes is not empty ? ' class=' ~ body_classes }} >

Edit: While this approach may seem counterintuitive at first it gives you the benefit of separating logic and presentation.编辑:虽然这种方法乍一看似乎违反直觉,但它为您提供了分离逻辑和表示的好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM