>我想在我的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$
在元数据中没有meta_description
的页面上,将生成以下 HTML:
<meta name="description" content=""/>
而我想要的是根本不生产标签。
我在transformedMetadataField
功能中做错了什么?
您需要返回 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" 总是将字段视为存在。 您必须从"field"复制代码才能在您想要的地方获得自己的 CA.empty 返回,就像我上面所做的那样(CA 是 Control.Applicative)。
对于后代来说,这是我最终得到的功能,这要归功于@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