Middleman:引用存储在markdown的数据文件中的URL

对于我的Middleman构建的网站,我存储了有关数据文件中所有页面的链接和其他信息 。

data/pages.yaml

 pageA: link: /some-long-url-subject-to-change.html name: PageA name info: Some other related info 

然后,在我的HAML模板( source/test.haml )中,我可以使用= data.pages.pageA.link打印pageA的相对路径。

现在,我想使用markdown语法按名称(pageA)引用该页面。

示例( source/test.html.haml ):

 .info :markdown This is some text with a [manual link](https://google.com) to somewhere. This is another text with a [data-referenced link](pageA) to that page. 

与第一个链接到Google的“手动链接”相同,我希望第二个链接使用存储在数据文件中的相对路径来创建链接。 我看到解决这个问题的一个解决方案是在用markdown渲染之前用= data.pages.pageA.link评估替换(pageA)文本。

我认为这可以通过创建自定义助手来实现,但我无法确定它。


我试图解决

我尝试编写一个自定义帮助程序来替换(pageA)文本,并在由markdown呈现之前评估= data.pages.pageA.link

我能够用来自数据的信息替换特定文本( pageA ),我还能够编写更通用的案例,用典型数据引用的显式文本替换所有数据引用。 但我无法在通用案例中替换data.pages.pageA.link以评估= data.pages.pageA.link

我的帮手:

 # Replace specific text with information from ``data/pages.yaml`` specific = text.gsub("pageA",data.pages.pageA.link) # Generic case: using explicit text generic = text.gsub(/\]\((.*?)\)/,'](data.pages.\1.link)') # Generic case: trying to use variable name, but getting explicit text generic = text.gsub(/\]\((.*?)\)/,'](#{data.pages.\1.link})') 

在我的test.html.haml使用helper:

 = myhelper("This is another text with a [data-referenced link](pageA) to that page.") 

打印specific变量给了我想要的东西( /some-long-url-subject-to-change.html )。 但是打印generic变量会产生纯文本,而不是数据文件中的信息。

我可能缺乏一些基本的Ruby知识,解决方案确实非常简单。

看起来好像你正在尝试编写自己的模板系统,这可能不是最好的主意。 首先,您需要编写一个正确解析Markdown并找到链接表示法的正则表达式。 然后,您需要评估您拉出的字符串以从数据中获取值。 最后,您需要用该值替换占位符。 我或多或少得到了在config.rb中使用此代码:

 helpers do def myhelper(text) page=/\]\((.*?)\)/.match(text)[1] link=eval( "data.pages.#{page}.link" ) text.gsub(page,link) end end 

但请不要使用此代码! 它很脆弱且容易出错。 更糟糕的是,有一种更简单的方法来做你想做的事情。 用test.haml.erb替换test.haml:

 .info :markdown This is some text with a [manual link](https://google.com) to somewhere. This is another text with a [data-referenced link](<%= data.pages.pageA.link %>) to that page. = myhelper("This is another text with a [data-referenced link](pageA) to that page.") 

.erb扩展名告诉Middleman将文件视为ERB模板 。 特别是,它将评估<%=%>之间的任何内容作为Ruby代码。 这意味着您可以跳过使用凌乱的辅助方法。 作为奖励,您不需要编写更多代码来获取其他数据:

  • <%= data.pages.pageA.name %> =>'PageA名称'
  • <%= data.pages.pageA.info %> =>'其他一些相关信息'

如果您需要执行一些更复杂的处理,例如迭代列表,则可以在模板本身中执行此操作。 这样更容易阅读和维护。

我还包括对辅助方法的调用作为对比。 除了使用现有的模板系统之外,目前还不太清楚。 此外,您一定会忘记在方法中包含所有相关的字符串,最后会出现断开的链接。

正如亚当建议的那样 ,你可能会更好地直接使用Markdown并跳过Haml 。

我不确定你到底遇到了什么。 以下是我的结论:

假设您的数据文件data/pages.yaml包含

 pageA: link: /some-long-url-subject-to-change.html name: PageA name info: Some other related info 

和你的模板test.haml.md.erb看起来像

 --- title: Test --- This is another text with a [<%= data.pages.pageA.name %>](<%= data.pages.pageA.link %>) to that page. 

输出应如下所示, PageA名称为可点击链接。

这是另一个带有该页面的PageA名称的文本。

您似乎遇到了降价解释的问题。 尝试将模板文件名从test.haml调整为test.haml.md.erb

这种结构告诉Middleman首先解释ERB位,然后是Markdown位,最后是HAML(如果不使用HAML,则为纯HTML)。