Get Current Path of Page in Middleman Layout File
Asked Answered
D

2

16

Is it possible to retrieve the current path of a page in a middleman file? For instance, if I have a layout file layout.erb with something like the following:

<%= page.path %>
<%= yield %>

and a test file index.html:

Testing

then when Middleman rendered the page I would get something like:

/index.html
Testing
Decurion answered 21/5, 2012 at 7:21 Comment(0)
F
43

Middleman also provides the current_page variable. current_page.path is the source path of this resource (relative to the source directory, without template extensions) and current_page.url is the path without the directory index (so foo/index.html becomes just foo).

<%= current_page.path %>
# -> index.html

<%= current_page.url %>
# -> /

Details from Middleman's Middleman::Sitemap::Resource rubydoc. http://rubydoc.info/github/middleman/middleman/Middleman/Sitemap/Resource

Fibrinogen answered 5/2, 2013 at 2:59 Comment(4)
This is probably the best way to get the current path considering it's exposed and documented.Decurion
Any idea how to get the hostname?Cleruchy
Is that possible if we get the port name ? I want to separate the staging url and production url @FibrinogenRamulose
Helpful to know: Middleman::Sitemap::Resource is the type of current_page (which is an alias of Middleman::TemplateContext.current_resource).Infare
D
2

The solution is:

<%= request.path %>
Decurion answered 21/5, 2012 at 9:17 Comment(3)
If I had to guess, I would say when Middleman builds the application it creates a server, requests the pageas in the application and writes the responses to files. But I honestly don't know.Decurion
@jackyalcine it is aliased to the resource object for the current path github.com/middleman/middleman/blob/…Unswerving
I don't know when this answer worked, but I'm getting undefined local variable or method 'request' today with Middleman 4.2Infare

© 2022 - 2024 — McMap. All rights reserved.