Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v3.9] Unable to use ob_start inside a custom twig method #4034

Closed
yellow1912 opened this issue Apr 18, 2024 · 3 comments
Closed

[v3.9] Unable to use ob_start inside a custom twig method #4034

yellow1912 opened this issue Apr 18, 2024 · 3 comments

Comments

@yellow1912
Copy link

Since the new version (I accidentally updated just yesterday), my calls to ob_start returns empty string now.

Before, I have 2 twig functions, which are simplified like this:

public function startInline()
{
    ob_start();
}

public function endInline()
{
    $content = ob_get_clean();
}

My twig may look like this:

{{ startInline() }}
something here
{{ endInline() }}

It used to work, but now with the new twig it always returns an empty string. Downgrading to 3.8 fixes the issue so I'm pretty sure this has something to do with the new code.

It was suggested that I could use the set block instead, but I want to know if and how I can update my code to work with the new version instead.

@stof
Copy link
Member

stof commented Apr 18, 2024

Those custom functions were relying on the internal implementation of Twig being based on echoing things in PHP.

Thus, using paired functions like that is a weird API: this is not what Twig functions are meant to do and it would be very easy to break things by not pairing them properly (which cannot be properly reported). This is a job for a Twig tag instead (which seems to be exactly what the {% set %} tag does btw).
I don't see any way to make those paired functions work with the new Twig internal implementation, as there is no way for functions to inject some capturing behavior between the 2 calls (which are unrelated as far as the Twig AST is concerned).

@stof
Copy link
Member

stof commented Apr 18, 2024

note that if endInline does more things than returning the content, you can do that by using a custom tag instead, for which the compilation would use a Twig\Node\CaptureNode to capture the output of the body and then do something with this output in the rest of the compiled code.

@fabpot
Copy link
Contributor

fabpot commented Apr 18, 2024

Closing for reasons explained by @stof

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants