简体   繁体   中英

How to add inline PHP to a .twig file?

I am trying to modify the <body> tag in a .twig file.

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?

Twig won't interpret PHP - it doesn't understand what it means.

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.

Assuming you call the context var body_classes you can then update the template to something like this:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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