Help with Grav lifecycle: can't get content generated from twig?

I have just learned that if I modify content from a plugin, it’s best to do it onPageContentProcessed so it will be cached. Working on another plugin, I have run into an issue that I don’t quite understand.

If I have a twig template that lists all of the page’s images, that content generated from twig does not seem to show up onPageContentProcessed. $event['page']->content() is null. I can do it all onOutputGenerated of course, but then there’s no caching. Any idea where I can grab that twig-generated content so my changes get cached?

Thank you for your time!

@Netzhexe,

{% block content %}
    {{ page.content|raw }}
{% endblock %}

A template has access to the page’s content (page.content) and injects it in the HTML to be send to the browser.

The page has no access to what has been generated by Twig, unless Twig is used inside Markdown (the page’s content).

A plugin can access the parsed content in event onPageContentProcessed and the final result (Twig + parsed content) in event onOutputGenerated.

You said:

$event['page']->content() is null

To verify, I’ve created a plugin and registered event onPageContentProcessed. It shows the parsed HTML (from Markdown) correctly.

public function onPageContentProcessed(Event $event) {
    $page = $event['page'];
    $content = $page->content();
}

Hey, thank you for your response! Just to clarify whether I’ve understood this correctly: I can’t modify content generated by a twig template via plugin in a way that gets cached. Yes?

In my case, the twig template generates an unordered list with all the images attached to the page. Markdown content is optional (think image gallery). And I would like to change that output a little, but NOT in twig.

@Netzhexe,

I can’t modify content generated by a twig template via plugin in a way that gets cached. Yes?

That’s correct, unless I stand corrected…

The way I see it, is that Grav caches the results of parsers/generators to save parsing time for a next request.

For example:

  • Results of image manipulation.
  • Markdown is being parsed into HTML. The resulting HTML is then being cached.
  • Twig is being parsed into PHP. That PHP is then being cached.
    However, that cached PHP is always executed on every page request.

And I would like to change that output

Not sure what you are trying to achieve. Do you wish to alter the ordering of the collection of images, or altering the resulting HTML of the gallery, or …

No, I need to add the sizes directive to the images without using Grav’s built-in functions, because they’re buggy :rofl: however, it seems you’re right and that there’s currently no way to do this except onOutputGenerated. So that’s all I wanted to know really, and since this is a temporary hotfix plugin and it works alright, there’s no need to bend over backwards trying to do this properly. :wink: