| トップ | 読書感想文 | Ukki |
How to set head tag content dynamically?
I'd like to set a meta tag for certain pages like this:

<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
</head>

A stackflow page has a solution using content_for.

content_for allows you to compose a snippet of HTML in a template and pull it from a different template.  For this particular case, content_for can be applied in a following way:

1) write the meta tag in a content_for block called :head in a page template.
2) view/layouts/application.erb to call yield(:head).

application.erb
<html>
<head>
<%= yield(:head) %>
</head>
...
</html>

index.erb
<%- content_for(:head) do -%>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<%- end -%>
here is regular body content.

<H1>dynamically put onload attribute to body tag</h1>
Similarly, onload attribute of body tag can be specified in a template.

application.erb
...
<body <%= yield(:onload) if @content_for_onload %>>
...

index.erb
...
<% content_for(:onload) do %>onload="initialize()"<% end %>
...

(11/07/2009)

Top
Index
Search on Ukki

login