Philip Kirkbride
Philip Kirkbride

Reputation: 22889

Jekyll extracting filename from url with Ruby

I'm trying to extract the file name from a url on Jekyll using this ruby snippet:

{% assign filename = page.url.split('/')[-1] | replace: '.html', '.md' %}

If I just use:

{% assign filename = page.url | replace: '.html', '.md' %}

I get back the url with the replaced file type but my .split('/')[-1] doesn't seem to work.

I tried running the following in standalone ruby to ensure my syntax was right, and it returned bird as expected:

"cat/dog/b­ird".split­('/')[-1]

Why doesn't the same syntax work in my Jekyll instance? Is it that page.url isn't a string, or something else?

Upvotes: 1

Views: 251

Answers (1)

marcanuy
marcanuy

Reputation: 23982

The problem is mixing ruby code with Liquid tags.

To extract the filename from a url in Jekyll you can use just pure Liquid template filters, using the equivalents of what you tried:

  • .split­('/') -> | split: '/'
  • [-1] -> | last

As an example with a custom URL:

{% assign url_example = "cat/dog/bird.html" %}
{% assign filename = url_example | split: '/' | last | replace: '.html', '.md' %}
{{filename}}

outputs:

bird.md

Upvotes: 5

Related Questions