Execute Ruby method on whole page in Middleman

走远了吗. 提交于 2019-12-11 15:30:17

问题


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.



来源:https://stackoverflow.com/questions/45692859/execute-ruby-method-on-whole-page-in-middleman

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!