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:

$product->product_min_price

What did I do wrong here?



62.8k
Accepted
answer

Try like that:

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

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



44.8k
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.