How to programmatically add a script or style sheet to a page in Docpad

How can I programmatically add a script or style tag to the page indicated on the YAML front meta (meta) page?

Assuming there is src/documents/posts/a.html.eco with the following contents:

 --- layout: default scripts: ['a.js'] --- Blog post that requires a special javascript 

and layout src/layouts/default.html.eco with the following contents:

 ... @getBlock('scripts').toHTML() </body> ... 

The end 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 should not have a link to /scripts/a.js

The tag above mentioned above simply shows that there may be some processing before entering the tag.

I tried many approaches using another events in the docpad.coffee file (including the approach taken from the docpad-plugin-livereload ), but every time I encountered the same problem - the script tag was applied to all pages instead of apply before a.html . Here is one of my attempts:

 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 also tried the render event, populateCollections (which is not documented, but I found it in the docpad-plugin-livereload ) and even extendTemplateData events and so far no luck.

I know there is a way to do this right inside the layout:

 @getBlock('scripts').add(@document.scripts or []) 

.. This is completely normal, and it really works as expected, however it does not provide enough freedom for me to manipulate the content before it is entered on the page. And even if it’s possible, I don’t like the idea of ​​having some heavy logic inside the layout template, I want it in the /docpad.coffee plugin

Hope this makes sense

+4
source share
1 answer

Try templateData.getBlock('scripts').add instead of docpad.getBlock('scripts').add

0
source

Source: https://habr.com/ru/post/1491026/


All Articles