使用 Haml 对象引用,例如 %div[@user]
Haml 有一个很好的功能,称为对象引用,我可以在其中做一些事情像这样:
%div[user]= user.name
它会生成这样的东西:
<div id="user_42" class="user">Billy</div>
有时,我想为该元素创建一个锚点,如下所示:
<a href="#user_42">Link to Billy</a>
我如何在 Haml 中做到这一点?有没有比这更简单的方法?:
%a{ :href=> "#user_#{user.id} } Link to Billy
编辑:可以使用自动包含的 Haml 助手?
Haml has a nice feature called Object reference where I can do something like this:
%div[user]= user.name
And it generates something like this:
<div id="user_42" class="user">Billy</div>
Sometimes, I want to create an anchor to that element, like this:
<a href="#user_42">Link to Billy</a>
How do I do that in Haml? Is there an easier way than this?:
%a{ :href=> "#user_#{user.id} } Link to Billy
Edit: Could be done with the automatically-included Haml helpers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,没有内置的方法可以做到这一点。如果这是您经常做的事情,我可能会创建一个辅助方法。
如果您需要处理更多情况(将选项传递给 link_to 等),您可以使该方法变得更复杂,但像这样简单的事情会清理它一些。生成链接变成:
如果你想使用 Haml 助手,你可以做一些非常类似的事情(但更令人困惑):
尽管如此,请注意,如果你是,则
underscore
方法将不可用在 Rails 之外执行此操作(这是我能想到避免使用 link_to 帮助器的唯一原因)。There's no built-in way to do this that I know of. I'd probably create a helper method if it's something you'll be doing a lot.
You could make the method more complex if you need to handle more cases (passing along options to link_to, etc.) but something simple like that would clean it up some. Generating the link becomes:
If you want to use Haml helpers, you could do something very similar (but much more confusing):
Although, be warned that the
underscore
method won't be available if you're doing this outside of Rails (which is the only reason I can think of for avoiding the link_to helper).