Setting a Global Variable (like a phone number)

Is there a way to set global variables (like a phone number as an example) that can then be pulled into a page or theme content?

My scenario is as follows:

  • I have a value for a discount that changes month to month.
  • I want a variable I can set in the content so i do not have to change each page manually.
    (ie. “Our monthly special is {var_discount} off”)


@polybizman Have a look at the docs on Site Configuration. Scroll down to “custom options”

You can create any option you like in this file and a good example is the blog: route: ‘/blog’ option that is accessible in your Twig templates with

Note: The doc is incorrect. Should be to access option.

You could add:

var_discount: 25%

And in your Twig:

<p>Our monthly special is {{ site.var_discount }} off</p>

Or if you prefer to use your own custom config file, have a look at Other Configuration Settings and Files

1 Like

Thanks for the quick response!

Looks good for template files but can I pull this variable in a page file?

Sorry, misread your question…

The only solution I can think of is adding an onPageContentRaw event to your theme or plugin and replace a placeholder for the variable in the content of the page.

If your page contains “Our monthly special is [discount] off” the function could look like:

public function onPageContentRaw(Event $e)
    // Get a variable from site.yaml
    $discount = $this->grav['config']->get('site.my_discount');

    // Get the current raw content
    $content = $e['page']->getRawContent();
    // Replace placeholder [discount] inside content of page
    $content = preg_replace('/\[discount\]/', $discount, $content);
    // Set the new content for the page

The event onPageContentRaw will only be fired once when the page is processed for the first time. Once the page is cached it will not run. When you update site.yaml, the cash will be marked dirty and onPageContentRaw will run again.

Note, for efficiency reasons, I would build in a check to prevent the function to be called on all pages…


You could process twig in your page:

This way, you could go with the solution provided by @pamtbaau.

And yet again a new gem of Grav revealed to me… Thanks.