How do I put image_tag in hash value in rails?

Asked 2 years ago, Updated 2 years ago, 53 views

Is there a way to put image_tag in hash value using Rails?

I created view_objects/ under app/ and put logic about view in it for each class.
To avoid writing logic to the view as much as possible.
Instance variables (hash type) created in the class in view_objects/ are expanded and displayed in view.

#view_objects/article_view.rb
class ArticleView
  attr_reader:header

  def initialize (data)
    @header={ 
      title —data.title,
      image: '=image_tag' + data.img
    }
  end
end


# view/article/index.html.slim

 table.table
 - @article_view.header.each do | key, value |
   tr
     td = key
     td = value

There is an image link in the hash type of the header, but the image from which the link is linked is not referenced, and only the URL is written in a string.
What should I do?

ruby-on-rails ruby

2022-09-30 19:06

1 Answers

Generally, it is not a good style to include specific tags other than View, but if you want to do so, you can use content_tag as follows:

class ArticleView
  include ActionView::Helpers::TagHelper
  attr_reader:header

  def initialize (data)
    @header={ 
      title —data.title,
      image:content_tag(:img, "",:src=>data.img),
    }
  end
end

Consider using Partial view, Helper, and Decorators (non-standard features such as Draper and ActiveDecorator).


2022-09-30 19:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.