Base 类
“道”依靠组件类来定义组件的渲染逻辑,每个组件类都继承自一个 Base 类 TaoOnRails::Components::Base
。
组件类里最重要的一个方法是 render(&block)
,接受一个可选的 &block 参数。Base 类为子类定义了默认的 render 方法,具体的内容是:
def render &block
if template = find_template
render_template template, &block
else
view.content_tag tag_name, nil, html_options, &block
end
end
可以看到,默认的 render 逻辑会先尝试去找到组件类对应的 partial 模版,如果能找到就渲染模版。
渲染模版
Base 类的 find_template
方法会按照约定在指定的路径查找 partial 模版。查找路径是通过组件类的名称推算出来的。例如,Todos::ItemsComponent
组件会尝试找到:
app/views/components/todos/_item.html.erb
如果找到了这个模版,组件类会渲染这个模版,并且把组件的实例(component)作为 local variable 传入模版,例如:
<%= content_tag component.tag_name, component.html_options do %>
<%= yield %><!-- 模版里可以 yield 传入 render 方法的 block -->
<% end %>
其中,tag_name
和 html_options
是 Base 类定义的 attribute,具体可以查看 API 文档
渲染 Custom Element
如果没有找到对应的 partial 模版,组件类会渲染一个 Custom HTML Element 作为组件的容器。Custom Element 的 tag name 是按照约定通过组件类的名称推算出来的。例如,Todos::ItemsComponent
对应的 tag name 是:
tao-todo-item
前缀 tao
是 Base 类定义的默认前缀,子类可以通过重写 tag_prefix
类方法来重新定义前缀,例如:
class ApplicationComponent < TaoOnRails::Components::Base
private
def self.tag_prefix
:zr
end
end