LoginSignup
7
10

More than 3 years have passed since last update.

【Rails】html.erbでの記述

Last updated at Posted at 2019-06-25

画像

railsで扱う画像は [app-assets-images] がルートとなる

<%= image_tag 'icon/hogehoge.png' %>

テキストリンク

<%= link_to "リンク名","リンクパス" %>

<%= link_to "ホーム",root_path %>

テキストリンク内にHTMLタグを入れる

xxx.html.erb
<%= link_to root_path  do %>ホーム<span>HOME</span><% end %>
xxx.html
<a href="/">ホーム<span>HOME</span></a>

画像リンク

<%= link_to image_tag('shop_images/hogehoge.png'),'/areas/hogehoge' %>

クラス/id 属性を追加する

<%= link_to 'トップページ', root_path, class: "top-large", id: "top" %>

CSSを読み込む

すべて読み込む呪文

※["\x83" on UTF-8]のエラーが出たことがあったが、cssではなく下記の通りjavascriptが影響していた

app/views/layouts/application.html.erb
<%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>

aタグをhoverしたときの修正

rails で動作させたとき、リンクをhoverバックカラーが黒になるのをデフォルトに戻す

hogehoge.css
a:hover{
  background-color: transparent;
}

参考:https://qiita.com/yukiji/items/3c43f8f6d54c561df3fd

Javascriptを読み込む

すべて読み込む呪文

app/views/layouts/application.html.erb
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>

[Encoding::InvalidByteSequenceError]["\x83" on UTF-8]のエラーが出ることがあるが、jsファイルの文字コードのエラーなので、utf-8で保存しなおすとエラーを回避できた。
image.png

HTMLの一部をテンプレート化する

ヘッダーやフッターなど共通するHtmlを外部化したいシーンは多々ありますよね。

共通部分のファイルを作成

保存場所:app/views/shared
ファイル名:_temp.html.erb
※テンプレート化する場合はアンダーバーを前に付ける

呼び出したい場所で以下の呪文を唱える

<%= render 'ディレクトリ名/部分テンプレート名' %>

<%= render 'shared/temp' %>
7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10