Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

General

Setting a Global Variable (like a phone number)

Solved by Amaury Hanser View solution

Started by Polybizman 8 years ago · 5 replies · 2312 views
8 years ago

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?

8 years ago

@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:

TXT
var_discount: 25%

And in your Twig:

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
last edited 07/12/18 by pamtbaau
8 years ago

Thanks for the quick response!

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

8 years ago

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:

PHP
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...

8 years ago

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

Suggested topics

Topic Participants Replies Views Activity
General · by Jerry Hunt, 4 days ago
2 82 11 hours ago
General · by pamtbaau, 16 hours ago
1 53 15 hours ago
General · by Andy Miller, 1 day ago
0 45 1 day ago
General · by Marcel, 12 months ago
6 347 5 days ago
General · by Duc , 5 days ago
3 41 5 days ago