19
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

link_toでネストした画像や文字列を 表示する方法

Posted at

ブランド一覧画面みたいなものを作ってるのですが、

  • ブランド1の画像(クリックでブランド詳細ページに飛べる)
    • ブランド1の説明文
  • ブランド2の画像(クリックでブランド詳細ページに飛べる)
    • ブランド2の説明文

という感じで、画像一覧を表示しつつ、画像クリックでそのブランドの詳細情報ページに飛べるようにリンクを貼って、さらにブランドについての説明文などを合わせて表示する処理を考えていたのですが、link_toで画像+文字列をどうやってネストすればいいのか地味にわからず、今後また似たことで悩みそうなのでまとめておきます

自分の開発環境

  • Mac OS X 10.8.5
  • Ruby 2.2.2
    • rbenv利用してインストールしてます
  • Rails 4.2
    • Haml使ってます。
    • haml (4.0.7)

です

はじめにlink_toの基本

link_toで

- @brands.each do |brand|
  = link_to "ブランド名", brand_path(brand) 

というのは知っていたものの、恥ずかしながら、文字列以外をどのように指定していいのか知らなかったです^^;

通常文字列を指定する箇所に、image_tag()をこんな感じで指定できるんですね


- @brands.each do |brand|
  = link_to image_tag("brand/#{brand.id}.jpg") ,brand_path(brand), class: "brand_image"

これを踏まえて、画像と一緒に、その画像についての説明文などを表示する方法を模索しました

最初考えたやり方

- @brands.each do |brand|
  = link_to image_tag("brand/#{brand.id}.jpg") ,brand_path(brand)
    %p
      = brand.name
      %br
      %span
      = brand.url

みたいな感じを考えたのですが、これだと構文エラーになってしまいました

こう書くのが正解でした

rails 3 link_to with nested content_tag to create <a href with nested span - how to?を見てたらブロックを使えばいいことがわかりました

- @brands.each do |brand|
  = link_to brands_path do
    = image_tag("#{brand.id}.jpg")
    %p
      = brand.name
      %br
      %span
      = brand.url

これ書き終えてからAPI Dock見たらしっかり書いてありましたね。こういう基本処理はドキュメントをあたるべきですね

19
21
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
19
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?