How to Render Arbitrary Script Attributes Using laminas-view's HeadScript Helper
Let’s Get Started
Recently, I decided to try out the privacy-focused fathom, as an alternative to Google Analytics, on the website for one of my books (Mezzio Essentials).
1 2 3 4 <script src="https://cdn.usefathom.com/script.js" data-site="ABCDEFG" defer></script>
This is used to identify the account for which the analytics data is being recorded for. Why? As they say on their website:
We are the proud inventors of cookieless website analytics and our software is compliant with GDPR, ePrivacy, PECR, CCPA, and COPPA.
|Check out the details of the Script element on MDN for more details.|
No, this is not a cheap plug for them, though I am really happy with the experience so far!
So what does this all have to do with the Mezzio Essentials site? Well, as you might expect from being a landing page for a book about PHP’s Mezzio Framework, it’s built with Mezzio, which uses Laminas components. Specifically, it uses laminas-view for the, rather simplistic, frontend view layer.
Given that, at first, I thought that all I’d need to do to get fathom analytics running was to add another call to
appendFile and change the first parameter to fathom's URI, such as in the example below.
However, that won’t include the custom attribute.
At this point, I had a look at
appendFile’s definition and noticed that the method supports a third parameter, an array of attributes.
So I changed the call to `appendFile to the example below:
However, after reloading the page, the custom attribute still wasn’t rendered. That’s when I noticed this, small, paragraph in the HeadScript docs:
Arbitrary Attributes are Disabled by Default
Given that, I added a call to
→setAllowArbitraryAttributes(true) at the end of the call to
appendFile, and the custom attributes were rendered.
For the sake of completeness, here is a complete example.
That’s how to render arbitrary script attributes using Laminas View’s HeadScript Helper
setAllowArbitraryAttributes(true) so that the attributes will be rendered on page load.
You might also be interested in...
- How to Use a CSRF Token in a Mezzio Application
- How to Manually Create a Mezzio Application
- Goodbye Master Zend Framework. So Long. Farewell.
- How to Set Up PHP Debugging with PhpStorm, Xdebug, and PHPUnit
- Why Is My Website So Slow?!
comments powered by Disqus