How-to library · Developer docs

How-to library

Task-shaped pages: a title that starts with a verb, the situation in a few lines, the steps, the working code in both engines, and why this way rather than another. Found from a search, done, and left.

Call a PHP function from a Smarty template, and find out why one is blocked

Call the function, do not pipe to it: trim($x) compiles, $x|trim does not. Ninety-eight PHP functions are callable, seven are allowed as modifiers, and Smarty's own modifiers always work. The error names the call.

Context

Context. Every Smarty template compiles under a security policy that lists which PHP functions may be called. A call outside the list does not render partially: the template fails to compile and the visitor gets the error page, with a message that names the call. A function and a modifier are checked against different lists: trim($x) is allowed, $x|trim is not, even though it is the same PHP function.

Steps

  1. Write the call in function form, inside braces: {trim($path, '/')}.
  2. If you wanted a modifier, use Smarty's own: |replace, |truncate, |escape, |lower and the rest always pass.
  3. When a page errors with modifier 'x' not allowed by security setting or PHP function 'x' not allowed, look the name up on the policy page: either it is a modifier that should be a function call, or it is off the list and has a replacement there.

Template code

Template code
{* allowed: function form *}
{trim($_request->getPath(), '/')}
{str_replace('-', ' ', $page->getSlug())}
{if strpos($_request->getPath(), '/docs') === 0}in docs{/if}
{implode(', ', array_filter($tags))}

{* compile error: PHP functions as modifiers *}
{* {$path|trim:'/'}   {$slug|str_replace:'-':' '} *}

{* allowed: Smarty's own modifiers, and the seven PHP ones *}
{$slug|replace:'-':' '}
{$title|truncate:60}
{$items|count}
{$data|json_encode}
{# Twig has no whitelist: any method the response model allows, and any core filter #}
{{ _request.getPath()|trim('/') }}
{{ page.getSlug()|replace({'-': ' '}) }}

Why this and not that

Not an attempt to loosen the policy: it is set by the platform for every site and a theme cannot change it. Not a helper in PHP: sites have no PHP of their own; the whitelist plus Smarty's modifiers cover string, array, date, hashing and regular-expression work, and the policy page lists a replacement for each common function that is missing (sprintf is |string_format, md5 is hash('md5', …), range is {for}). One modifier to never commit: |dd dumps and stops with a 500, on production too.

Go deeper

Was this page helpful?

Your answer goes to the docs team.