ERB和HAML如何转换if条件语句?

11

我正在开始学习HAML,并且正在努力将我的第一个文件转换为HAML格式。 看起来正确的省略“- end”:

- if current_user
= link_to 'Edit Profile', edit_user_path(current_user.id)
= link_to 'Logout', logout_path
- else
= link_to 'Register', new_user_path
= link_to 'Login', login_path

我能帮你:

app/views/layouts/application.html.haml:28: syntax error, unexpected kENSURE, expecting kEND
app/views/layouts/application.html.haml:30: syntax error, unexpected $end, expecting kEND

当涉及到逻辑操作时,需要理解以下几个概念:
- if current_user
= link_to 'Edit Profile', edit_user_path(current_user.id)
= link_to 'Logout', logout_path
- else
= link_to 'Register', new_user_path
= link_to 'Login', login_path
- end

我能帮你:

You don't need to use "- end" in Haml. Use indentation instead:
- if foo?
  %strong Foo!
- else
  Not foo.

我该如何在HAML中使这个条件语句生效?

2
你的问题中已经包含了答案...错误信息会告诉你该怎么做。 - nitecoder
3个回答

21

HAML是基于缩进的,解析器可能会很棘手。请更换。

- if current_user
= link_to 'Edit Profile', edit_user_path(current_user.id)
= link_to 'Logout', logout_path
- else
= link_to 'Register', new_user_path
= link_to 'Login', login_path

使用

- if current_user
  = link_to 'Edit Profile', edit_user_path(current_user.id)
  = link_to 'Logout', logout_path
- else
  = link_to 'Register', new_user_path
  = link_to 'Login', login_path

试着去做一下,注意看link_to行的缩进发生了变化。


缩进不一致:使用5个空格进行缩进,但文档的其余部分是使用2个空格缩进的。 - sleepycat
1
你缩进了太多空格 - 或者太少了。你能发布你的整个模板吗? - Natalie Weizenbaum
我重新查看了间距,我认为你是正确的。我认为我已经修复了缩进问题,但现在我遇到了这个错误:/app/models/user_session.rb:5: 语法错误,意外的 '<' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ^ /app/models/user_session.rb:8: 语法错误,意外的 '<'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> ^ /app/models/user_session.rb:8: 语法错误,意外的 tIDENTIFIER,期望 $end <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> ^ 我错过了什么? - sleepycat
那似乎与Haml无关。听起来你不小心把HTML放进了一个模型类文件中。 - Chuck
@Chuck:HAML不用于模型,而是用于视图。 @sleepycat:你的HAML文件中有HTML。请进一步阅读HAML并查找一些示例。 - Mike Trpcic
实际上,尽管有些牵强,Chuck还是成功了。我曾试图从Github保存一个模型文件,但出现了一堆HTML而不是任何Ruby代码。真是一团糟!视图中的HAML内容也有点混乱,但我通过你们提供的技巧解决了这个问题。感谢大家! - sleepycat

3
- if current_user
  = link_to 'Edit Profile', edit_user_path(current_user.id)
  = link_to 'Logout', logout_path
- else
  = link_to 'Register', new_user_path
  = link_to 'Login', login_path

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接