Hi,
I’m wondering if Middleman can generate a full URL for image paths?
Example: if I write /img/foo.png in content source, the same will appear in the generated HTML and feed readers cannot render these images.
Hi,
I’m wondering if Middleman can generate a full URL for image paths?
Example: if I write /img/foo.png in content source, the same will appear in the generated HTML and feed readers cannot render these images.
Hi marko,
You would have to explicitly set which domain you were deploying to, but here’s how you could get an image_url
helper. Inside config.rb
:
# Used for generating absolute URLs
set :protocol, "http://"
set :host, "example.com"
set :port, 80
helpers do
def host_with_port
[host, optional_port].compact.join(':')
end
def optional_port
port unless port.to_i == 80
end
def image_url(source)
protocol + host_with_port + image_path(source)
end
end
configure :development do
# Used for generating absolute URLs
set :host, Middleman::PreviewServer.host
set :port, Middleman::PreviewServer.port
end
You could then use the helper like this:
<%= image_tag image_url("vacation.jpg"), alt: "Trip to Mars" %>
Which would produce:
<img src="http://example.com/images/vacation.jpg" alt="Trip to Mars">
Hi Aupajo,
Thanks for your answer, that’s it.
Since my blog posts are in Markdown, I realized that in order to use helpers they should have .md.erb extension.
Now I’m having an issue with making markdown-syntax work in .erb files which contain Ruby snippets, but I’ll start another issue / thread for that.
Hi,
is there any way to get Aupajo’s Helper to work with hashed image urls (using asset_hash)?
Thanks!
Hi @benebun,
The helper should work with asset_hash just fine. It uses image_path
, which is handled by asset_hash.
A few updates to this, since it seemed to break for me during the upgrade to Middleman 4. Specifically:
Middleman::PreviewServer doesn’t seem to work to access the current host or port during development anymore. I’m not sure what the new “proper” way to do this is, but I always use the same hostname and port for accessing during development, so I just hardcoded it.
You can no longer access config variables in config.rb using the plain syntax above. Rather, the helpers block now looks as follows:
helpers do
def host_with_port
[config[:host], optional_port].compact.join(’:’)
end
def optional_port
config[:port] unless config[:port].to_i == 80
end
def image_url(source)
config[:protocol] + host_with_port + image_path(source)
end
end
Hope that helps someone (or, you know, me, searching for the same problem yet again three years down the line) in the future.