-->

Execute Ruby method on whole page in Middleman

2019-09-16 03:26发布

问题:

On my Middleman-built website, I need to execute specific Ruby code on the contents of all the pages (templates).

For example, if I had following helper in my config.rb:

def myexample(text)
    text.gsub("dog","cat")
end

And in my test.html.haml:

= myexample("Some text about a dog.")

My previewed and generated /test.html would read:

Some text about a cat.

However, I am using several different ways to output text that needs to be modified, most notably through HAML's :markdown filter, so I would prefer not to wrap everything in the = myexample("Text") helper.

I would like to be able to run Ruby code that would take contents of all the pages (preferably) or generated HTML output (if the first option is not possible) as an argument passed to such helper.

Ideally, this code would be run in both the development and build environments, but if that's not possible, build is enough.

Is it possible to do so?

PS. In my specific case, I use a shorthand notation to reference other pages and then I use a regular expression and eval() in order to replace them with relative links from data files.

回答1:

ActionController::Base has the render_to_string method which will give you the normal HTML output from rendering a partial or page, but in string format. This would allow you to grab the rendered HTML and modify it before finally rendering it for real as an inline template.

In your controller:

rendered_html = render_to_string 'your_template_or_partial'
# do stuff to rendered_html
render inline: rendered_html.html_safe, layout: 'layouts/application'

The html_safe method makes sure Rails knows it's safe to render this as HTML. You do NOT want to do this if user input is being rendered and you have not sanitized it!!!!

If you don't want it to use a layout when rendering, just remove the :layout argument.