2

I have a template for an MkDocs site, which uses Jinja2. I am trying to add a link to a PDF version of each page. The PDF always has the same name as the markdown file. So I am trying to add a link in the template that will automatically target the correct PDF for each page. This feels cleaner than having the writers add a manual link to every page.

<a href="{{ page.url|url }}.pdf">Download</a>

The above is almost correct, but there is a '/' at the end of all the URLs. Meaning the result is:

page/url/slug/.pdf

Neither MkDocs nor Jinja seem to provide a filter to remove trailing slashes, so I am wondering if it's possible to use regex to remove it. I believe that would be as simple as \/$? However, I can't see from the docs how to apply a regex filter in Jinja?

  • 1
    Have you seen this question: https://stackoverflow.com/questions/12791216/how-do-i-use-regular-expressions-in-jinja2 ? – Jan Feb 11 '19 at 13:08
  • I found replace() in the docs, but I don't see how to use it without replacing ALL /, whereas I only want to lose the last one? And I was hoping there was a simpler solution than custom filters =/ – Starfall Projects Feb 11 '19 at 13:14

3 Answers3

5

You can do something like this:

{{ "string/".rstrip("/") }}

Worked for me.

ouflak
  • 2,458
  • 10
  • 44
  • 49
mwgmwg
  • 61
  • 1
  • 3
1

So I found a workaround for my specific case, but it's nasty:

<a href='{{ config.site_url }}{{ page.url | reverse | replace("/", "", 1) | reverse }}.pdf'>Download</a>
  1. Prepend the site URL
  2. Get the current page URL, reverse it, use replace with the optional count parameter to remove the FIRST '/', then reverse it again to get it back in the right order
  3. Append '.pdf'

According to one of the answers to the question linked by Jan above, you can't simply use regex in Jinja2 without getting into custom filters.

0
<a href="{{ page.url | replace("/$", "")}}.pdf">Download</a>

where $ is the end of the line / end of the string.

Therefore, /$ means the / at the end.

virolino
  • 2,073
  • 5
  • 21
  • 2
    Unfortunately this doesn't work - I don't believe you can pass regex to replace(), only the exact string you want to find and replace. I just tried it out and it had no effect (presumably because it went looking for exactly /$ in the URL and didn't find it – Starfall Projects Feb 12 '19 at 17:14
  • Thank you for the comment. Initially I provided the following attempt of solution: I do not know Jinja2, but in your case, if it is applicable, just use the substring of length N-1. That will just forget the final `/` – virolino Feb 13 '19 at 05:18