What is the difference between render and yield in Rails

前端 未结 3 717
自闭症患者
自闭症患者 2021-02-13 11:00

Can someone explain the difference between \"<%= render %>\" and \"<%= yield %> with <% content_for :partial do %>/

3条回答
  •  不思量自难忘°
    2021-02-13 11:39

    yield

    Ruby code (Proc class) and takes your block and does what it is supposed to do with it. Yield is also fast compared with other Ruby based ways of doing the same thing. I'd assume (and I only) use it in the layouts because it's quick and I mindlessly do what's normal in Rails. yield is also used to pass content to a specific spot in your layout. I often have <%= yield :head %> in the head, just above the head tag, so that I can pass random weirdness that sometimes comes up.

    Common Uses:

    • Mostly just used in layouts
    • (if you are fancy/inclined to do so in a Model) as a true Ruby Proc statement.

    render

    Rails code that you pass arguments to that, as the docs say, "Renders the content that will be returned to the browser as the response body". partials, actions, text, files...etc.

    Common Uses:

    Used in both views and the controller.

提交回复
热议问题