Automatically add class to img tag for every blog post

Hello,

I’m trying to do the following:

I want every image included inline in an blog post to have a specific CSS class added.

Here is an example:

The blog post source

I have a 2015-04-23-de-ce-eu.html.markdown file.
Inside that file I wrote the following line:

![my-image](2015-04-23-de-ce-eu/de-ce-eu-header.png)

The generated page source (actual result)

The above line generates the following HTML:

<img alt="my-image" src="/articole/2015/de-ce-eu/de-ce-eu-header.png">

The expected result

What I would to achieve is to generate the following HTML:

<img alt="my-image" src="/articole/2015/de-ce-eu/de-ce-eu-header.png" class="responsive-image">

I couldn’t find any documentation about how to make this happen for an img tag inside a blog post written in markdown.

So far I’ve generated the following possible workarounds:

  1. Not using markdown for writing blog posts and write HTML and ERB.
  2. Adding a JavaScript code which automatically adds that class to every img tag in the page

I still think there is a more elegant solution then those two.
For example I found on the internet an example of a helper which automatically adds a class to body tag.

Thank you,
L

I’ve found the answer.
I could hook into image_tag and add my class only for current_paths starting with blog_prefix.

Here is my solution added helpers section in config.

  def image_tag( path, params = {} )
    blog_prefix = blog_controller.try(:options).try(:prefix).try(:gsub, "/", "")
    if current_path =~ %r{^#{blog_prefix}}
      classes = params[:class].try(:split, " ") || []
      classes << "responsive-img"
    end
    params[:class] = classes.try(:join, "")
    super( path, params )
  end

LE: Fixed a typo in the join line.

1 Like

If you are using Kramdown, which is the default Markdown engine for Middleman, this is the syntax for extra attributes:

![my-image](2015-04-23-de-ce-eu/de-ce-eu-header.png){:class="responsive-img"}

It works with anchors too.

1 Like

@jpmelguizo yes I’m using Kramdown.

Yes, this was something that I was searching for.

Thank you.