Pergunta

Highly related questions to help me refactor and streamline my code.

First

My view starts with <% provide(:title, 'My Title') %>

But then in the rest of the view, in headers or in paragraphs or what not, 'My Title' repeats itself a LOT... is there a way that I can just call it again? I tried, for example: <h4>:title</h4> which did not work.

Second

Also in the same view, I repeat, if you're interested, please contact me (with a link) a lot. I'd like to also replace this sentence with a symbol of some kind.

Now initially, I had thought about using a global variable like so

<p>Yada dada beginning text. <%= @@contactme %> </p>

And then delcaring it in the controller (btw, reason it's global is because multiple methods refer to the same view, it's actually a partial), but the problem is that I'm not even sure it's possible to declare a global variable with HTML and routes in it like so.

class Controller do
    @@contactme = "If you're interested, please <a href='<%= new_contact_path %>'>please contact me</a>".html_safe
end

And even if it were possible, it's not exactly working for me. Before the variable even has a chance to render I get: uninitialized class variable @@contactme in ActionView::CompiledTemplates

Thanks!

Foi útil?

Solução

First:

application.html.erb

<%= content_for :title %>

posts/index.html.erb # for example

<% content_for :title do %>
  Awesome title
<% end %>

More information here: http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

Second:

class Post
  CONTACTME = "If you're interested, please <a href='/contacts/new'>please contact me</a>".html_safe
end

application.html.erb

<%= Post::CONTACTME %>

Outras dicas

For the first, like Rahul said, use yeild.

For the second, I am not sure generating views within controller is a good behaviour, and you will also face multiple layer erb rendering (<% tag with another <% tag) in this case, (which I am not sure if it will work)

try this:

class Controller do
  @contactme = "If you're interested, #{link_to 'please contact me', new_contact_path}"
end

Edit:

new_contact_path may only be used in views, not controllers. Please try to use partials for your case.

create app/views/shared/_contactme.html.erb with following content:

If you're interested, <%= link_to 'please contact me', new_contact_path %>

Then in your original views

<p>Yada dada beginning text. <%= render 'shared/contactme' %></p>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top