Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and use variable in VIews Template in Rails ?

I am still new to ruby and rails and is looking to create a variable so I can use it over and over again in the views template. For example,my code right now is

<title>Home Page</title>
<h3>Welcome to my Home Page</h3>

Now I want to make this "Home Page" as variable or symbol so I can just use that variable/symbol rather than typing the string over and over, how to do it ?

Thanks

like image 669
iCyborg Avatar asked Mar 02 '13 07:03

iCyborg


People also ask

What is Local_assigns?

local_assigns is a Rails view helper method that you can check whether this partial has been provided with local variables or not. Here you render a partial with some values, the headline and person will become accessible with predefined value.

What keyword is used in a layout to identify a section where content from the view should be inserted?

Within the context of a layout, <%= yield %> identifies a section where content from the view template should be inserted. The simplest way to use this is to have a single yield, into which the entire contents of the view currently being rendered is inserted.

What are instance variables Ruby?

In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data. We say that objects can: Do things.


1 Answers

When I first read your question, I thought you were asking for this, but I realize this is different.

Michael Hartl's amazing Ruby-on-Rails Tutorial demonstrates my favorite method for doing this, which is to create an instance variable that gets referenced in the layout exactly the way you want.

rails_root/app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  attr_accessor :extra_title
  ...

That makes @extra_title accessible in all controllers. Now inside one particular controller:

rails_root/app/controllers/things_controller.rb

class ThingsController < ApplicationController

  def index
    @extra_title = "| Things"
    ...

Ok, so what is this all for? Oh right, we wanted to use this in a layout:

rails_root/app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Best. App. Ever. <%= @extra_title %></title>
...

And now you're riding the Rails.

like image 120
Austin Mullins Avatar answered Sep 23 '22 17:09

Austin Mullins