简体   繁体   中英

Parsing a 'template' in rails (alternatives to gsub)

I have a 'template' system in my CMS rails app. Basically the whole HTML template is stored in a database column and it has key code in the string (like <!--THEME_Body--> ) that gets replaced with content generated by the application.

I use an actual layout to render the template. All that is in the layout is:

<%= generate_theme.gsub!('<!--THEME_Body-->', yield) -%>

That helper takes the correct theme and further gsubs other area like Meta data and Breadcrumbs.

I'm just wondering if there's a better way to go about this? Perhaps using content_for or something like that?

That's a pretty good way of going about it, although I would make use of Ruby's sexy syntax to combine all the lines into something a little more syntactically correct - it speeds the script up and it looks a damn sight nicer too!

tags = {
    '<!--THEME_Body-->' => yield,
    '<!--THEME_Head-->' => yield(:head),
    '<!--STYLESHEET-->' => stylesheet_link_tag('application')
}

tags.each { |str, rep| generate_theme.gsub!(str, rep) }

Bear in mind that this code should not go in a view - it should ideally be put in a model, as it's to do with the application's data, but it could also go in a helper somewhere. If it's an instance variable in a model, you could just call

generate_theme.parse

And that code could be executed - it looks a lot better and sticks to the standard MVC convention of cleaning up the view as much as possible.

Jamie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM