Setting a Global Variable (like a phone number)


#1

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”)

Help?


#2

@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 system.blog.route

Note: The doc is incorrect. Should be site.blog.route 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


#3

Thanks for the quick response!

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


#4

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
    $e['page']->setRawContent($content);
}

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…


#5

Hello,

You could process twig in your page:
https://learn.getgrav.org/content/headers#process

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


#6

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