简体   繁体   English

在rails中解析“模板”(gsub的替代方案)

[英]Parsing a 'template' in rails (alternatives to gsub)

I have a 'template' system in my CMS rails app. 我的CMS Rails应用程序中有一个“模板”系统。 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. 基本上,整个HTML模板都存储在数据库列中,并且字符串中具有键代码(例如<!--THEME_Body--> ),该键代码已由应用程序生成的内容替换。

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? 也许使用content_for或类似的东西?

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! 这是一个很好的解决方法,尽管我将利用Ruby的性感语法将所有行组合成语法上更正确的东西-它加快了脚本的速度,看上去也真不错!

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. 而且该代码可以执行-看起来好多了,并遵循尽可能多地清理视图的标准MVC约定。

Jamie 杰米

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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