phug-php / phug

Phug - The Pug Template Engine for PHP
https://phug.selfbuild.fr
MIT License
62 stars 3 forks source link

How to pass variable to filter? #33

Closed acelot closed 6 years ago

acelot commented 6 years ago

Hello,

I encountered an issue with the following code:

span
  :format-date('DD-MM-YYY')
    $article['publication_date']

$article['publication_date'] is a DateTime.

I expected to get:

<span>30-03-2018</span>

But I actually get:

[TypeError] Argument 1 passed to {closure}() must be an instance of DateTime, string given

My Renderer instance:

$renderer = new \Phug\Renderer([
    'filters' => [
        'format-date' => function (\DateTime $date, $args = []) {
            return $date->format($args[0]);
        }
    ]
]);
kylekatarnls commented 6 years ago

Filters have options (attributes), no arguments:

span
  :format-date(format='DD-MM-YYY')
    $article['publication_date']
$renderer = new \Phug\Renderer([
    'filters' => [
        'format-date' => function (\DateTime $date, $options) {
            return $date->format($options['format']);
        },
    ],
]);

Please tell me if you get trouble, I will re-open this issue.

acelot commented 6 years ago

@kylekatarnls the problem is not about getting an options in filter. Problem is to pass value (variable) into filter. Is it correct to pass a variable to filter as in a template? Because I'm getting [string] "$article['publication_date']" instead of \DateTime instance in $date argument.

TorbenKoehn commented 6 years ago

Hello,

the content of a filter is usually given in plain-text, since it can be anything (e.g. JavaScript, CSS or something completely different like Markdown or even pure PHP) The filter is responsible for parsing the text content.

A better way to format dates within Pug is by using normal PHP functions

span= $article['publication_date']->format('d-m-Y')

It's also more pure and looks better, PHP-wise :)


Edit: If you really want to pass it as an option, you could probably use something like this:

span
    :format-date(format='DD-MM-YYYY', value=$article['publication_date'])

and then

$renderer = new \Phug\Renderer([
    'filters' => [
        'format-date' => function ($content, $options) {
            return $options['value']->format($options['format']);
        },
    ],
]);

but as you can see, it's rather redundant