2

我想在我的 Hakyll 站点的上下文中添加一个字段。如果元数据中存在某个键,那么我想转换相应的值并将其包含在上下文中。如果元数据中不存在密钥,则不应将任何内容添加到上下文中。

我写了这个函数,应该做我所描述的:

-- | Creates a new field based on the item's metadata. If the metadata field is
-- not present then no field will actually be created. Otherwise, the value will
-- be passed to the given function and the result of that function will be used
-- as the field's value.
transformedMetadataField :: String -> String -> (String -> String) -> Context a
transformedMetadataField key itemName f = field key $ \item -> do
    fieldValue <- getMetadataField (itemIdentifier item) itemName
    return $ maybe (fail $ "Value of " ++ itemName ++ " is missing") f fieldValue

但是,如果元数据字段不存在,那么这仍会在上下文中插入一个字段,并将空字符串作为其值。例如,我在我的上下文中有这一行:

transformedMetadataField "meta_description" "meta_description" escapeHtml

我有这个模板:

$if(meta_description)$
    <meta name="description" content="$meta_description$"/>
$endif$

在元数据中没有 no 的页面上meta_description,会生成以下 HTML:

    <meta name="description" content=""/>

而我想要的是根本不生产任何标签。

transformedMetadataField我在我的职能中做错了什么?

4

2 回答 2

3

您需要返回 Control.Applicative 的“空”以使字段完全不存在。我自己的代码中的一个例子:

-- What we're trying to do is produce a field that *doesn't* match
-- key in the case where the metadata "header" is not set to "no" or
-- "false"; matching it and returning false or whatever
-- (makeHeaderField above) isn't working, so any call to "field" is
-- guaranteed to not work
makeHeaderField :: String -> Context a
makeHeaderField key = Context $ \k _ i -> do
    if key == k then do
      value <- getMetadataField (itemIdentifier i) "header"
      if isJust value then
        if elem (fromJust value) [ "no", "No", "false", "False" ] then
          -- Compiler is an instance of Alternative from
          -- Control.Applicative ; see Hakyll/Core/Compiler/Internal.hs
          CA.empty
        else
          return $ StringField $ fromJust value
      else
        return $ StringField "yes makeheader"
    else
      CA.empty

哦,我忘了:正如我上面的代码注释所指定的,在这种情况下你不能使用 hakyll “field” 函数,因为在字段名称匹配的情况下,“field”总是将该字段视为存在。您必须从“字段”复制代码才能在 CA.empty 返回您想要的地方,就像我在上面所做的那样(CA 是 Control.Applicative)。

于 2017-11-02T00:51:52.753 回答
1

对于后代,这是我最终得到的功能,这要感谢@rlpowell 的回答。

-- | Creates a new field based on the item's metadata. If the metadata
-- field is not present then no field will actually be created.
-- Otherwise, the value will be passed to the given function and the
-- result of that function will be used as the field's value.
transformedMetadataField :: String -> String -> (String -> String) -> Context a
transformedMetadataField newKey originalKey f = Context $ \k _ i -> do
    if k == newKey
       then do
           value <- getMetadataField (itemIdentifier i) originalKey
           maybe empty (return . StringField . f) value
       else empty
于 2017-11-04T17:32:09.890 回答