docpad

How do I insert unique meta tags per page using docpad events


I'm trying to write a docpad plugin that will allow me to insert meta tags unique to each page, for example og:title or og:description. I've been able to accomplish this globally with the populateCollections event for global values, but have not been able to do this per page.

I'd like for this to work without the need for a template function so that the meta tag is inserted automatically based on the document's meta. One way might be to grab the contentRendered value in the writeBefore event and do string manipulation that way, but that seems hacky.

Any ideas?


Solution

  • This worked for what I needed. Basically, I'm getting the rendered content right before the file is written using the writeBefore event, and doing a very simple string replace which adds the meta tags and their unique values, which is pulled from the model in the collection.

    writeBefore: (opts) ->
            docPad = @docPad
            templateData = docpad.getTemplateData()
            siteUrl = templateData.site.url
    
            for model in opts.collection.models
                if model.get('outExtension') == 'html'
                    url = @getTag('og:url', siteUrl+model.get('url')) 
                    title = @getTag('og:title', model.get('title'))
                    content = model.get('contentRendered')
                    if content
                        content = content.replace(/<\/title>/, '</title>'+url+title+description)
                        model.set('contentRendered', content)
    # Helper
    getTag: (ogName, data) ->
        return "\n    <meta property=\"#{ogName}\" content=\"#{data}\" />"