HAML 条件标签
HAML conditional tags
我目前正在使用 HAML 作为模板语言在 rails 应用上构建一个 ruby。我希望创建一个条件,该条件根据是否满足来定义标签,否则它会定义不同的标签。我知道我可以这样写:
- if ordered
%ol
- else
%ul
但这并不是特别枯燥,需要我复制大部分代码。有没有一种非常直接的方法来解决这个问题?我应该研究 ruby 逻辑来找到它吗?
谢谢
定义一个助手。我们将引入 ordered
选项来选择标签,其余的都传递给标签。
# app/helpers/application_helper.rb
module ApplicationHelper
def list_tag(ordered: false, **opts)
kind = ordered ? :ol : :ul
haml_tag kind, **opts do
yield
end
end
end
然后,
-# some_view.html.haml
%p
Here's a list:
- list_tag ordered: false, class: 'some_class' do
- @list.each do |item|
%li
= item
如果您需要在不同的视图中执行此逻辑,我认为您可以采用两种方法:
1.制作一个部分并在需要的地方渲染它。如果您需要传递变量,请使用 local_assigns
_my_list.html.haml
- if ordered
%ol
- else
%ul
使用它
render 'partials/my_list', ordered: ordered
2。制作你自己的帮手
def my_list(ordered)
if ordered
content_tag(:ol, class: 'my-class') do
# more logic here
# use concat if you need to use more html blocks
end else
content_tag(:ul, class: 'my-class') do
# more logic here
# use concat if you need to use more html blocks
end
end
end
使用它
= my_list(ordered)
您可以将有序变量保留在视图之外,并在助手内部处理整个逻辑。
如果你问自己用什么,那么here的第一个答案很好。
您可以使用content_tag
方法如下。 content_tag documentation
= content_tag(ordered ? "ol" : "ul")
如果你多次需要它,你可以把它放在辅助方法中
module Listhelper
def list(ordered, html_options = {})
= content_tag(ordered ? "ol" : "ul")
end
end
通过 = list(your_variables)
从视图中调用它
我目前正在使用 HAML 作为模板语言在 rails 应用上构建一个 ruby。我希望创建一个条件,该条件根据是否满足来定义标签,否则它会定义不同的标签。我知道我可以这样写:
- if ordered
%ol
- else
%ul
但这并不是特别枯燥,需要我复制大部分代码。有没有一种非常直接的方法来解决这个问题?我应该研究 ruby 逻辑来找到它吗?
谢谢
定义一个助手。我们将引入 ordered
选项来选择标签,其余的都传递给标签。
# app/helpers/application_helper.rb
module ApplicationHelper
def list_tag(ordered: false, **opts)
kind = ordered ? :ol : :ul
haml_tag kind, **opts do
yield
end
end
end
然后,
-# some_view.html.haml
%p
Here's a list:
- list_tag ordered: false, class: 'some_class' do
- @list.each do |item|
%li
= item
如果您需要在不同的视图中执行此逻辑,我认为您可以采用两种方法:
1.制作一个部分并在需要的地方渲染它。如果您需要传递变量,请使用 local_assigns
_my_list.html.haml
- if ordered
%ol
- else
%ul
使用它
render 'partials/my_list', ordered: ordered
2。制作你自己的帮手
def my_list(ordered)
if ordered
content_tag(:ol, class: 'my-class') do
# more logic here
# use concat if you need to use more html blocks
end else
content_tag(:ul, class: 'my-class') do
# more logic here
# use concat if you need to use more html blocks
end
end
end
使用它
= my_list(ordered)
您可以将有序变量保留在视图之外,并在助手内部处理整个逻辑。
如果你问自己用什么,那么here的第一个答案很好。
您可以使用content_tag
方法如下。 content_tag documentation
= content_tag(ordered ? "ol" : "ul")
如果你多次需要它,你可以把它放在辅助方法中
module Listhelper
def list(ordered, html_options = {})
= content_tag(ordered ? "ol" : "ul")
end
end
通过 = list(your_variables)