【问题标题】:Add class to custom form_for label将类添加到自定义 form_for 标签
【发布时间】:2014-05-27 03:10:00
【问题描述】:

如何将自定义类添加到 form_for else 语句?

<%= form_for(@user) do |f| %>

      .
      .
      .
      <%= f.label :name, 
        if @user.errors[:name].blank?
          'Name'
        else
          'Name ' + @user.errors[:name].to_sentence
        end
      %>

我试过了:

else
  'Name ' + @user.errors[:name].to_sentence, class: "some_class"
end

也试过了:

else
   'Name ' + @user.errors[:name].to_sentence, :class => "some_class"
end

但两者都会产生意外错误。

我只是自定义输入标签以在表单提交时显示验证错误,并想更改文本颜色。

【问题讨论】:

    标签: ruby-on-rails ruby erb form-for


    【解决方案1】:

    我猜你可以一行完成:

    <%= f.label :name, (@user.errors[:name].blank? 'Name' : 'Name ' + @user.errors[:name].to_sentence) %>
    

    然后:

    <% if @user.errors[:name].blank? %>
      <%= f.label :name, 'Name' %>
    <% else %>
      <%= f.label :name, 'Name ' + @user.errors[:name].to_sentence, :class => "some_class"  %>
    <% end %>
    

    【讨论】:

    • 是的,if/else 语句的格式很长,因为我只想在一个输出中添加一个类。在这种情况下,else 语句的输出应该将一个类添加到 f.label :name
    • 谢谢 zishe,知道为什么我原来的方法是相同的,在一组 erb 标签中不起作用,但你的在每一行都有标签吗?
    • 您不能使用&lt;% ... %&gt; 多行。你应该把它们放在每一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2011-01-28
    • 1970-01-01
    • 2012-10-11
    • 2016-07-10
    • 1970-01-01
    相关资源
    最近更新 更多