Search code examples
twiggrav

Grav CMS: how to show/hide parts of the page depending on conditions?


The Grav's documentation clearly describes how a whole page or a folder could be hidden from unregistered users. It also describes how a whole page could be seen only by particular user groups.

But what about pieces of a page, let's say, some links or a private info I want to show on some conditions?

Ok, for registered users I found a snippet at Login plugin docs:

{% if grav.user.authenticated %}
    content for registered users goes here
{% endif %}

But going wider - how can I show/hide pieces of a particular page depending on some custom logic in PHP code, i.e. not necessarily user related?

I'm thinking about a twig/shortcode plugin, something like:

{% if some.custom.condition.or.PHP.function %}
   hidden content goes here
{% endif %}

or

[hidden_if_something] hidden content goes here [/hidden_if_something]

But not sure how exactly this should be implemented. So working examples would be appreciated. Thanks.


Solution

  • There is a recipe in the Grav documentation here. This provides an example of how to render the output of a PHP code result in a twig template.

    In the example they create a plugin, and implement a twig extension providing access to a php function. They can then simply call that php function like in a twig template.

    {{ example() }}
    

    Following that example, you can implement whatever logic you would like in php, and call the function in a twig if statement.

    {% if example() == true %}
       your conditional output
    {% endif %