asas1asas200
asas1asas200

Reputation: 11

Should I transmit local variable to partial template or just use instance variable

I have a partial template, and I call it like this:

<%= render 'postBlock' %>

In this template:

<%= content_tag(:h1, @post.title) %>
<%= markdown(@post.content) %>

I am confused that should I try the method like below:

<%= render 'postBlock', post: @post %>
<%= content_tag(:h1, post.title) %>
<%= markdown(post.content) %>

Can someone give me a suggestion?

Upvotes: 1

Views: 34

Answers (2)

Neeraj Amoli
Neeraj Amoli

Reputation: 1026

Both ways are good, use locals where you load a page and from there you want to pass a value to the partial template, you can pass easily. using locals like below

<%= render partial: 'postBlock', locals: {message: message} %>

and in that partials, you can use a local variable message like this <%= message %>

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

Either works but my preference would be post: @post as it would let you reuse the partial in other circumstances where you might substitute something other than @post... for example if you were doing several posts...

<% @posts.each do |post| %>
  <%= render 'postBlock', post: post %>
<% end %>

And that would require no change to the partial if you need to do this in future.

Upvotes: 1

Related Questions