How can I programmatically add script or stylesheet tag to a page specified in page's YAML front matter (meta)?
Assuming there is src/documents/posts/a.html.eco
with following contents:
---
layout: default
scripts: ['a.js']
---
Blog post that requires a special javascript
and layout src/layouts/default.html.eco
with following contents:
...
@getBlock('scripts').toHTML()
</body>
...
The final result for posts/a.html
should be:
...
<!-- some extra stuff that was added when processing script tag -->
<script scr="/scripts/a.js"></script>
</body>
...
..while other pages shouldn't have a reference to /scripts/a.js
The comment above tag is just to show that there may be some processing envolved before injecting the tag.
I tried many approaches using different events
in docpad.coffee
file (including approach taken from docpad-plugin-livereload
plugin) but every time I was facing the same problem - script tag was applied to all pages instead of being applied to a.html
only. Here is one of my tries:
renderDocument: (opts) ->
{extension,templateData,file,content} = opts
if extension == 'html' and scripts = file.get('scripts')
if typeof scripts != 'undefined'
scripts.forEach (scriptName) ->
@docpad.getBlock('scripts').add('<!-- custom script tag here -->')
I've also tried render
event, populateCollections
(which is not documented however I found it in docpad-plugin-livereload
plugin) and even extendTemplateData
events and no luck so far.
I know there is a method of doing this right inside a layout:
@getBlock('scripts').add(@document.scripts or [])
..which is totally fine and it really works as expected however it doesn't seem to provide enough freedom for me to manipulate the content before it's injected to a page.. And even if it's possible I won't like the idea of having some heavy logic inside layout template, I want it to be in a plugin/docpad.coffee
Hopefully that makes sense