morteza mortezaie
morteza mortezaie

Reputation: 1564

how to use php and volt parameter together?

I am using Volt and PHP in phalcon volt partial

I want to iterate a loop and in the loop I have php code that accept a parameter

this is my code

{% for header in headers %}
<th>
    <?=gettext( {{header}} );?>
</th>
{% endfor %}

here header is a parameter that is used in php code

but I get this error

enter image description here

what is the right way to rewrite this code

Upvotes: -2

Views: 626

Answers (3)

Chess
Chess

Reputation: 36

You can configure some services in a better way to help you solve this issue.

If you define your view service like:

    $di->set('view', function () {
        $view = new View();
        $view->setDI($this);
        $view->setViewsDir(__DIR__ . '/views/');

        $view->registerEngines([
            '.volt'  => 'voltShared'
        ]);

        return $view;
    });

You can define your voltShared service improving the volt compiler with custom functions in this way:

$di->setShared('voltShared', function ($view) use ($di) {
    $config = $this->getConfig();

    $volt = new VoltEngine($view, $this);
    $volt->setOptions([
        'autoescape'        => false,
        'compileAlways'     => true,
        'stat'              => true,
        'compiledSeparator' => '_',
        'compiledPath'      => $config->application->cacheDir.'volt/',
    ]);

    // We add some custom functions
    $compiler = $volt->getCompiler();
    $compiler->addFunction('gettext', function ($resolvedArgs) {
        return 'gettext('.$resolvedArgs.')';
    })

    return $volt;
});

Upvotes: 1

Fenikkusu
Fenikkusu

Reputation: 94

I'm guessing you are trying to use a raw PHP function here, so correct me if I'm wrong. Unfortunately I forget the exact reason this is (I learned a long time), but you have to manually register PHP functions in the Volt Engine in order to use them. This can be done using the addFunction method of the Engine will allow you to add them. I thought it had been resolved that this wasn't needed anymore, but it was reported in https://github.com/phalcon/cphalcon/pull/12841.

Anyways, using addFunction: I've used the below to get around this:

foreach (get_defined_functions()['Internal'] as $functionName) {
    $voltEngine->addFunction($functionName, $functionName);
}

You have to put this in the code that initializes the volt engine.

Upvotes: 0

Justinas
Justinas

Reputation: 43549

Reading documentation shows that echo command is using {{ }} instead of normal PHP tag <?= ?>:

{% for header in headers %}
<th>
    {{ gettext(header) }}
</th>
{% endfor %}

Upvotes: -1

Related Questions