0

ユーザーがクリックしてテキスト領域に入力できるメッセージの提案をいくつか作成しています。表示される場合、一般的な文字列はユーザ​​ーの詳細とともにレンダリングする必要があります。

これは私がやろうとしていることですが、この例では、データベースから取得されていない html コード化されたメッセージを使用しています:

<ul>
    <li><a><%= "#{@user.name} is the best" %></a></li>
    <li><a><%= "#{@user.name} is the worst" %></a></li>
    <li><a><%= "I think #{@user.name} is the best" %></a></li>
    <li><a><%= "I think #{@user.name} is the worst" %></a></li>
</ul>

データベースに「プレースホルダー」を使用して一般的な文字列を保存し、ビュー内の値のみを計算できるようにしたいと考えています。

これは、データベース(シードファイル)に文字列を作成しようとした方法です

Suggestion.create(message: '#{@user.name} is the best')
Suggestion.create(message: '<%= #{@user.name} %> is the best')
Suggestion.create(message: '<%= @user.name %> is the best')

ビューでは、反復があります

<%= suggestion.message %>

ビューがレンダリングされる前に、ルビー コードをビューに追加しようとしています。おそらくばかげた考えです。

これはhtmlソースに表示されるものです

&lt;%= @user.name %&gt; is the best
&lt;%= #{@user.name} %&gt; is the best
#{@user.name} is the best

これは似たようなものですが、変数が各メッセージ内の異なる場所にあるため機能しないメッセージを追加します。

<ul>
    <% @suggestions.each do |message| %>
        <li><a><%= "#{@user.name} message" %></a></li>
    <% end %>
</ul>
4

3 に答える 3

2

テンプレートのセットをデータベースに保存し、それらのテンプレートをビューにレンダリングしようとしています。

液体を使用する必要があります

http://liquidmarkup.org/

スニペットの例:

<ul id="products">
  {% for product in products %}
    <li>
      <h2>{{ product.title }}</h2>
      Only {{ product.price | format_as_money }}

      <p>{{ product.description | prettyprint | truncate: 200  }}</p>

    </li>
  {% endfor %}
</ul>

レンダリングするコード

Liquid::Template.parse(template).render 'products' => Product.find(:all)

これをどのように使用できますか:

class Suggestion < AR::Base
  validate :message, presence: true

  def render_with(user)
    Liquid::Template.parse(message).render user: user
  end
end


Suggestion.create(message: "{{user.name}} is the best")
Suggestion.create(message: "{{user.name}} is the worst")
Suggestion.create(message: "{{user.name}} is the awesome")

<ul>
  <% Suggestion.all.each do |suggestion| %>
    <li><%= suggestion.render_with(@user) %>
  <% end %>
</ul>
于 2013-10-02T14:25:09.923 に答える
1

これがあなたが望むものかどうかはわかりませんが、次の場合に機能する@user可能性のある解決策をいくつか示しnilます。

"#{@user.try(:name)} is the best in the biz"
"%s is the best in the biz" % @user.try(:name)
"#{name} is the best in the biz" % { name: @user.try(:name) }

try nil で呼び出された場合は nil を返します。

HTML 出力がまだエスケープされている場合は、次のいずれかを試してください。

raw(expression)
expression.html_safe
于 2013-10-02T13:01:01.300 に答える
0

このメッセージを各ユーザーに表示する場合は、メソッド呼び出しにする必要があります。

class Suggestion < AR::Base
  belongs_to :user

  def default_message
    "#{user.name} is the best"
  end
end

@user       = User.new(name: "Bob")
@suggestion = Suggestion.create(user: @user)
@suggestion.default_message #=> "Bob is the best"
于 2013-10-02T13:02:52.783 に答える