Is it possible to use strait PHP in our templates along side of Twig and or instead of Twig?

If so how does one go about it?

2 Answers 2


No this is not possible.

If you really need PHP, you can write a plugin with one of the following:

  • a Template Variable class, which can be accessed from your templates via craft.myPluginHandle
  • a Twig extension, which can add its own global filters, functions, or tags, etc.
  • a controller, which can execute PHP before calling $this->renderTemplate(...)
  • a template hook, which allows PHP code to access and modify the current template variable context, wherever the {% hook %} tag is placed.

Why Twig anyway?

The question to use php in templates comes up every once in a while, but there are good reasons for not using it.

For example if Craft changes its code you don't have to worry about your templates. The upcoming update of the Yii framework would force you to rewrite all your templates if they were written in php.

There is also a great article from Fabien Potencier on this topic -- tl;dr php is too verbose for templating.

  • Thanks Brad, I didn't even knew there were template hooks.
    – Victor
    Jul 3, 2014 at 17:15
  • 1
    Little known, but very handy feature!
    – Brad Bell
    Jul 3, 2014 at 17:17

In craft 3 it is actually possible.

{{ craft.app.view.evaluateDynamicContent('phpinfo();') }}

As you can see above, php code is passed as string to evaluateDynamicContent function. On inside, evaluateDynamicContent is just running eval function.

Now, even if you can do this, doesn't mean that you should. Before doing this, consider if you have other alternatives for doing what you want to achieve. Using php code inside template can run you into all kind of unpredicted security issues.

  • +1 because it's all true... but as piotrpog mentioned, this is playing with fire and you should try hard to avoid it!
    – Lindsey D
    Jan 8, 2019 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.