Middleman: referencing URL stored in a data file from markdown

Viewed 475

For my Middleman-built website I have stored links and other information about all pages in a data file.

data/pages.yaml:

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

Then, in my HAML template (source/test.haml), I can print relative path to pageA with = data.pages.pageA.link.

Now, I want to use markdown syntax to reference that page by its name (pageA).

Example (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.

In the same way as first "manual link" links to Google, I would like second link to use relative path stored in data file to create a link. One solution that I see to solve this problem would be to replace (pageA) text with evaluation of = data.pages.pageA.link prior to it being rendered by markdown.

I assume this would be possible by creating custom helper, but I can't quite nail it.


My attempt at solution

I tried to write a custom helper to replace (pageA) text with evaluation of = data.pages.pageA.link prior to it being rendered by markdown.

I was able to replace specific text (pageA) with information from data and I was also able to write more generic case, which replaces all data references with explicit text of typical data reference. But I can't get to replace data.pages.pageA.link in generic case for evaluation of = data.pages.pageA.link.

My helper:

# 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})')

Usage of helper in my test.html.haml:

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

Printing specific variable gives me what I want (/some-long-url-subject-to-change.html). But printing generic variable results in plain text, instead of information from data file.

It is possible that I am lacking some basic Ruby knowledge and solution is indeed very simple.

2 Answers
Related