Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How can I pass an object variable to custom function which added to Volt?

I added one function to Volt like this:

$compiler->addFunction('formatPrice', function ($price){
    echo($price); die();

In Volt template:

<span class="p-price-number">{{ formatPrice(product.product_price) }}</span>

product.product_price is a string as 100000.

But I received this result on the browser:


What did I do wrong here?


Try like that:

$compiler->addFunction('formatPrice', function($resolvedArgs, $exprArgs){
    return 'yourFunction(' . $resolvedArgs . ')';

Also no need to echo inside function when doing {{ }} in volt

edited Aug '16

You need to return a string in the compiler functions. If you execute a statement like echo ... directly then it will just output that into the buffer at the very moment.