1

I’m new to Twig, having just recently built a blog using Grav CMS, which I’m also new to.

I added the following to one of my partials:

{% set csp_nonce = 'nonce-' ~ random_string(20)|base64_encode %}

I could then access it later in the same template as follows:

    <meta http-equiv="X-My-Nonce" content="{{ csp_nonce }}">

This was a quick way to see if I had been successful by viewing the generated source code.

However as I want to use that csp_nonce value multiple times in one page, so I can allow inline styles and scripts with a content security policy, without resorting to using 'unsafe-inline', I thought I’d pop that code in a template of its own and call that when needed. I’ve tried include, embed/endembed, use and extends but all I seem to achieve is either a twig error about having content outside a block or no error but anywhere I’ve included the child template and then try to access the csp_nonce value it’s empty (so I’m guessing I’m falling foul of a scoping issue but struggling to get my head around it.

Any help greatly appreciated!

EDIT: I managed to get it to work by just putting the {% set csp_nonce... into each parent twig. Which for now will do as now the value is available to use everywhere I need it. But I know there’s a better way I’m just not seeing.

Graham Gold
  • 2,435
  • 2
  • 25
  • 34

0 Answers0