4

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

Sergey Lukin
  • 471
  • 2
  • 17
  • Have you tried the FrontEnd plugin? https://github.com/sergeche/docpad-plugin-frontend If that works for you say so, so I can put it in an answer. :) – greduan Jul 12 '13 at 14:54
  • Thanks for comment. Yes, I've checked that plugin. It doesn't utilize Docpad's `@getBlock` to add scripts however, it creates custom @assets object, populates it and then iterates through it in the layout. I'm looking for solution that utilizes native Docpad's `@getBlock` helper. – Sergey Lukin Jul 12 '13 at 19:57

1 Answers1

0

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

balupton
  • 47,113
  • 32
  • 131
  • 182