Rails:是否可以使用 HAML 语法编写视图助手?
在重构过程中,只需复制 HAML 模板的一部分并将其粘贴到助手的代码中就会非常方便。目前在这种情况下 1) 我必须从头开始重写视图的该部分 2) 我必须使用像 content_tag 或 haml_tag 这样的详细语法。
我知道可以使用 HAML 系统定义部分作为助手。虽然 1)对我来说,为每个小函数创建一个单独的文件是不方便的 2)partial 的调用语法非常冗长。
理想情况下,我希望我的 *_helper 类看起来像这样:
- def some_helper(*its_args)
.some_class
= some_ruby_expression
%some_tag#some_id
- another_expression do
etc
或者至少像这样:
define_haml_helper :some_helper, [:arg1, :arg2], %{
.some_class
= some_ruby_expression
%some_tag#some_id
- another_expression do
etc
}
有一个插件可以解决我的问题吗?
或者,也许您可以描述如何将 HAML 片段重构为可重用元素(帮助程序/函数/部分/构建器/等)?
During refactoring it would be quite handy just to copy part of HAML template and paste it to helper's code. Currently in such cases 1) I have to rewrite that part of view from scratch 2) I have to use that verbose syntax like content_tag or haml_tag.
I know that it's possible to define partials with HAML systax that will serve as helper. Though 1) as for me it's inconvinient to create a separate file for each small tiny function 2) invocation syntax for partial is quite verbose.
Ideally i'd like my *_helper class to look like this:
- def some_helper(*its_args)
.some_class
= some_ruby_expression
%some_tag#some_id
- another_expression do
etc
or at least like this:
define_haml_helper :some_helper, [:arg1, :arg2], %{
.some_class
= some_ruby_expression
%some_tag#some_id
- another_expression do
etc
}
Is there a plugin that solves my issue?
Alternatively, maybe you can describe how do you refactor HAML snippets to reusable elements (helpers/functions/partials/builders/etc)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 参考:
这会启动一个新的 Haml 引擎并渲染它。
From the reference:
This initiates a new Haml engine and renders it.
如果您想要的只是一个可重用的小片段的方法,那么带有局部变量的部分怎么样? http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
If all you are after is a method for small reusable snippets, how about partials with local variables? http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
Haml 现在有一个 capture_haml 方法,您可以使用它来完成此任务。
以下是有关
capture_haml
的更多信息的链接:http://haml.info/docs/yardoc/Haml/Helpers.html #capture_haml-instance_method
Haml now has a
capture_haml
method that you can use to accomplish this.Here is a link with more info on
capture_haml
:http://haml.info/docs/yardoc/Haml/Helpers.html#capture_haml-instance_method
我将heredoc用于此类目的:
这种方式在变量范围方面存在很多问题,因此,如上所述,更正确的方法是为此使用部分。
UPD1:这是关于如何解决范围问题的解决方案:
UPD2:更好的解决方案(建立在互联网上):
I used heredoc for such purposes:
This way has a lot of issues with a scope of variables, so, as mentioned above, the much more correct way is to use partials for this.
UPD1: here is a solution on how to solve issues with scope:
UPD2: even better solution(founded on the internet):