【问题标题】:How do I insert unique meta tags per page using docpad events如何使用 docpad 事件为每页插入唯一的元标记
【发布时间】:2013-11-10 23:20:03
【问题描述】:

我正在尝试编写一个 docpad 插件,它允许我插入每个页面唯一的元标记,例如 og:title 或 og:description。我已经能够通过针对全局值的 populateCollections 事件在全局范围内完成此操作,但无法按页面执行此操作。

我希望它能够在不需要模板函数的情况下工作,以便根据文档的元自动插入元标记。一种方法可能是在 writeBefore 事件中获取 contentRendered 值并以这种方式进行字符串操作,但这似乎很老套。

有什么想法吗?

【问题讨论】:

    标签: docpad


    【解决方案1】:

    这可以满足我的需要。基本上,我在使用writeBefore 事件写入文件之前获取渲染的内容,并执行一个非常简单的字符串替换,添加元标记及其唯一值,这些值是从集合中的模型中提取的。

    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}\" />"
    

    【讨论】:

      【解决方案2】:

      David 的回答很好,如果有人遇到与我相同的问题,请留下这个。

      检查元标记是否损坏,如果是 - 不要渲染:

      renderBefore: (opts) ->
              for model in opts.collection.models
                 if model.get('date').toLocaleDateString()=='Invalid Date'
                    model.set('write', false)
                    docpad.log model.get('title')+' has broken date format!\n\n\n\n\n' 
                    false
      

      【讨论】:

        【解决方案3】:

        我在集合中使用部分。像这样在文档中添加需要的内容:

        ```
        title: Meetings and Events
        layout: page
        description: "This is my custom description."
        tags: ['resources']
        pageOrder: 3
        pageclass: rc-events
        ```
        

        我需要逐页自定义 CSS 类。然后你可以像这样在你的默认模板中调用它。

        <div id="main" class="container <%= @document.pageclass %>">
        

        meta应该是一样的

        <meta name="description" content="<%= @document.description) %>" />
        

        或检查您的docpad.coffee 文件并根据默认站点值和@document 值组合准备内容的辅助函数。然后你可以调用类似默认的东西:

        <meta name="description" content="<%= @getPreparedDescription() %>" />
        

        这是由这个辅助函数构建的:

        # Get the prepared site/document description
        getPreparedDescription: ->
            # if we have a document description, then we should use that, otherwise use the site's description
            @document.description or @site.description
        

        【讨论】:

          猜你喜欢
          • 2018-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-11
          • 2018-12-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多