Execute Ruby method on whole page in Middleman

In my Middleman site, I need to execute some Ruby code on the content of all pages (templates).

For example, if I had the following helper in mine config.rb

:

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

      

And in mine test.html.haml

:

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

      

My viewed and generated one /test.html

will read:

Some text about a cat.

      

However, I use several different ways to output the text that needs to be changed, especially with a HAML filter :markdown

, so I would rather not wrap everything in a helper = myexample("Text")

.

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

Ideally, this code will run in both development environments and assembly, but if that is not possible, assembly is sufficient.

Can this be done?

PS. In my particular case, I use shorthand notation to link to other pages, and then I use regex and eval()

to replace them with relative links from data files
.

0


source to share


1 answer


ActionController :: Base has a method render_to_string

that will give you HTML standard output from partial or partial display, but in string format. This will allow you to grab the rendered HTML and modify it before finally making it 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 method html_safe

ensures that Rails can safely render this as HTML. You do NOT want to do this if the user input is rendered and you haven't sanitized it !!!!

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

0


source







All Articles