0

I have a helper that defines the time template like this:

protected array $_defaultConfig = [
    'templates' => [
`        'time' => '<time{{attrs}}><i class="far fa-clock fa-sm fa-fw"></i> {{text}}</time>',
    ],
];

So I have the time() method:

public function time(string $text, array $options = []): string
{
    $attrs = $this->templater()->formatAttributes(options: $options, exclude: ['icon']);

    return $this->formatTemplate(name: 'time', data: compact('attrs', 'text'));
}

So far, everything works fine. For example, with:

$this->Helper->time(text: '5 days ago');

output:

<time><i class="far fa-clock fa-sm fa-fw"></i> 5 days ago</time>

Now I would like to understand how I can modify the template (and possibly add variables to it) using the $options argument, so in the single method call (let's say "inline", then).

For example:

$this->Helper->time(
    text: '5 days ago',
    options: [
        'templates' => ['time' => '<span{{attrs}}><i class="far fa-clock fa-sm fa-fw"></i> {{text}} - {{subtext}}</span>'],
        'templateVars' => ['subtext' => 'Another text'],
    ]
);

As usual, I get nothing (in fact, I should also exclude these options for formatAttributes()).

I understand that I need to somehow update the template and parse the new variables into my method, but I can't find any documentation on this.

I currently find it works like this here:

public function time(string $text, array $options = []): string
{
    $options += [
        'templateVars' => []
    ];

    if (isset($options['templates']['time'])) {
        $this->setTemplates(['time' => $options['templates']['time']]);
    } else {
        $this->setTemplates(['time' => $this->getConfig('templates.time')]);
    }

    $attrs = $this->templater()->formatAttributes(options: $options, exclude: ['icon', 'templates']);

    return $this->formatTemplate(name: 'time', data: compact('attrs', 'text') + $options['templateVars']);
}

I wonder if it is correct and reasonable, maybe it is, but it doesn't seem like much to me. Of course here I have to call the setTemplates() method even when $options['templates']['time'] is not present, to reset the default template (otherwise subsequent calls to the method will continue to use the updated one).

So I ask for some useful information, including some examples from some existing helper or documentation (which I didn't find). Thanks.

(obviously the one exposed is an example case, otherwise I would be quicker to use the tag() method of HtmlHelper)

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.