Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield and provide() inside template

Tags:

Could anyone give clear explanation on how provide() works inside the view ? I have read official documentation but what really bothers me is this, if I define in the beginning of a template

<% provide(:title, 'Help') %>

and then later I have this line of code

<%= yield :title %> 

what really happens in the background ? I know that yield is supposed to call code block. What would be code block in this context?

like image 480
Zed Avatar asked Jul 03 '13 20:07

Zed


People also ask

How can you tell Rails to render without a layout?

2.2. By default, if you use the :plain option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option and use the . text. erb extension for the layout file.

What is render partial in rails?

Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

What is content for in rails?

The content_for method allows us to insert content into a named yield block in our layout. For example, this view would work with the layout that we just saw: <% content_for :head do %> <title>A simple page</title> <% end %> <p>Hello, Rails!</


1 Answers

provide stores a block of markup in an identifier for later use. In this case, 'Help' in the symbol :title. The provide is enclosed in <% %> to indicate it is executing this code and not printing out in the view.

yield in this case just spits that block back out. The yield is enclosed in <%= %> to indicate it is being printed out into the view.

Think of it as setting a variable and printing out a variable.

See: http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-provide for more information. Note that provide is really a wrapper for content_for so that's where the good stuff is in that link.

like image 188
Jeff Price Avatar answered Sep 20 '22 11:09

Jeff Price