Allow to capture content and then render it into a different place:
content_for :assets do js_tag :jquery end # later in views yield_content :assets #=> '<script src="jquery.js" type="text/javascript"></script>'
Use content_for?
to check whether content block exists for some key:
p content_for?(:assets) #=> #<Proc:0x00... p content_for?(:blah) #=> nil
It is also possible to pass any variables into content block:
content_for :account do |name, email| form_tag! do input_tag(value: name) + input_tag(value: email) end end # somewhere in views yield_content :account, :foo, 'foo@bar.com' #=> '<form><input value="foo"><input value="foo@bar.com"></form>'
Please note that content block will be executed every time you call yield_content
.
If you are using same content block multiple times on same page please consider to assign the result to a variable and use it repeatedly to avoid performance decreasing.
[ contents ↑ ]
Execute given content block and return the result.
Useful when you need to display same snippet multiple times and want it rendered only once.
html = capture_html do js_tag(:jquery) + css_tag(:ui) end puts html #=> <script src="jquery.js" type="text/javascript"></script> #=> <link href="ui.css" media="all" type="text/css" rel="stylesheet">
[ contents ↑ ]