苗条的Ruby模板:第2部分

在这个迷你系列的第二部分和最后一部分中,我们将以有关输出Ruby代码,插值,纯文本以及如何根据需要自定义Slim的部分结束本介绍。 在那篇文章之后,您应该准备一些苗条的动作。

输出代码

您已经了解了如何在模板中使用Ruby。 本节为您提供了使用此功能所需的全部功能。 在第一篇文章中,我们已经在模板中使用了Ruby。 让我提醒您我的意思:

html
  head
    title
    = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true
    = javascript_include_tag 'application', 'data-turbolinks-track' => true
    = csrf_meta_tags

如您所见,在这个head标签中,我们已经使用了Rails中的几种方法来处理样式和JavaScript东西,没什么大不了的。 执行Ruby代码所需要做的只是在其前面加上一个equals =符号。 如果您的代码需要跨多行,只需在每行末尾添加反斜杠\ ,然后继续进行下一行即可。 如果你结束一个逗号线, ,那么你不需要反斜线。 如果你问我,很好的一点接触。

让我们看另一个更具体的例子。 编写表格通常很麻烦-许多样板代码,大量重复以及所有这些在ERB中令人恐惧的<%= %>符号。 这很快就会变得凌乱。 会更好一点吧?

ERB

<%= form_for @agent do |f| %>

  <%= f.label      :name %>
  <%= f.text_field :name %>

  <%= f.label      :number %>
  <%= f.text_field :number %>

  <%= f.label      :licence_to_kill %>
  <%= f.check_box  :licence_to_kill %>

  <%= f.label      :gambler %>
  <%= f.check_box  :gambler %>

  <%= f.label      :womanizer %>
  <%= f.check_box  :womanizer %>

  <%= f.submit %>

<% end %>

创建新的@agent对象需要写很多东西,不是吗? Slim使您可以更简洁地处理此问题。 我们只是保持等号并摆脱大多数其他问题。 多田

= form_for @agent do |f|

  = f.label      :name
  = f.text_field :name

  = f.label      :number
  = f.text_field :number

  = f.label      :licence_to_kill
  = f.check_box  :licence_to_kill

  = f.label      :gambler
  = f.check_box  :gambler

  = f.label      :womanizer
  = f.check_box  :womanizer

  = f.submit

您可以清楚地看到为什么将此项目称为Slim。 多余的脂肪消失了。 不要告诉我你不喜欢你所看到的-我知道你正在挖掘它! 只是一个=号,您可以使用Ruby代码填充标记-当然,在这种情况下是从Rails中填充标记。 而且,当您将它与最终页面上呈现HTML进行比较时,很难忽略Slim到底有多紧凑。

HTML输出
<form action="/" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" />

  <input type="hidden" name="authenticity_token" value="+P2I801EkEVBlsMgDo9g9/XgwwQfCBd1eoOBkFmgAHE4bxYi9HGUjEjsNwNMnEadV2tbDtYvQhFb4s/SNMXYtw==" />

  <label for="agent_name">Name</label>
  <input type="text" name="agent[name]" id="agent_name" />

  <label for="agent_number">Number</label>
  <input type="text" name="agent[number]" id="agent_number" />

  <label for="agent_licence_to_kill">Licence to kill</label>
  <input name="agent[licence_to_kill]" type="hidden" value="0" />
  <input type="checkbox" value="1" name="agent[licence_to_kill]" id="agent_licence_to_kill" />

  <label for="agent_gambler">Gambler</label>
  <input name="agent[gambler]" type="hidden" value="0" />
  <input type="checkbox" value="1" name="agent[gambler]" id="agent_gambler" />

  <label for="agent_womanizer">Womanizer</label>
  <input name="agent[womanizer]" type="hidden" value="0" />
  <input type="checkbox" value="1" name="agent[womanizer]" id="agent_womanizer" />

  <input type="submit" name="commit" value="Save Agent" />

</form>

还记得Slim核心团队所指导的最初问题:“完成这项工作所需的最低要求是什么?” 当您看一下HTML的最终输出时,我想可以说Slim已经相当成功地回答了这个问题,这毫无疑问。 我想举几个小例子,让您有更多的机会适应Slim的外观。

这个ERB片段...

<%= render "shared/agents", collection: @agents %>

…在Slim中成为:

= render "shared/agents", collection: @agents

ERB

<h2>Agents</h2>

<ul>
  <% @agents.each do |agent| %>
    <li class='agent'>
      <div>Name: <%=            agent.name %></div>
      <div>Number: <%=          agent.number %></div>
      <div>Licence to kill: <%= agent.licence_to_kill %></div>
    </li>
  <% end %>
</ul>
h2 Agents
ul
  - @agents.each do |agent|
    li.agent
      div
        | Name: 
        = agent.name
      div
        | Number: 
        = agent.number
      div
        | Licence to kill: 
        = agent.licence_to_kill

您还可以通过插值以更简化的方式编写此代码。 但是,您不想对那一个发疯。 然后看起来像这样:

h2 Agents
ul
  - @agents.each do |agent|
    li.agent
      div Name:            #{agent.name}
      div Number:          #{agent.number}
      div Licence to kill: #{agent.licence_to_kill}

文字插补

我之前曾简要提到过这一点,但是由于它是输出Ruby代码的一种形式,因此它也属于本节。 当然,您也可以在Slim模板中使用来自Ruby的标准文本插值。

h2 Welcome Mr. #{misix_agent.surname}! I expect you to die!

 h2 Welcome Mr. \#{misix_agent.surname}! I expect you to die!
HTML
<h2>
  Welcome Mr. Bond! I expect you to die!
</h2>

<h2>
  Welcome Mr. \#{misix_agent.surname}! I expect you to die!
</h2>

如上所示,简单的前导反斜杠\避免插值。

控制码

一路走来。 假设您要在视图中使用几个条件。 与Haml相似,您表示不应该通过简单的破折号-将Ruby代码输出到页面上。 您已经在上面的示例中看到了这一点,在该示例中,我们使用 该代码 遍历 @agents 而不显示代码的特定部分。

尽管您应该尽可能地避免使用各种条件,并为此类情况找到更好的OOP解决方案(这是另一回事了),但它们看起来应该是这样的:

- if current_user.role == "admin"
  p#admintxt | Welcome back my master!
  = link_to "Edit Profile", edit_user_path(:current)
  = link_to "Logout",       logout_path
- elsif current_user
  = link_to "Edit Profile", edit_user_path(:current)
  = link_to "Logout",       logout_path
- else
  = link_to "Register",     new_user_path
  = link_to "Login",        login_path

ERB

<% if current_user.role == "admin" %>
  <p id="admintxt">Welcome back my master!</p>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout",       logout_path %>
<% elsif current_user %>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout",       logout_path %>
<% else %>
  <%= link_to "Register",     new_user_path %>
  <%= link_to "Login",        login_path %>
<% end %>

如果要输出代码而没有HTML转义,只需使用两个等号== 。 而已!

在继续之前,我绝对应该花时间提及这一点:希望您知道,大量的视图代码(在我们的上下文中又称为Ruby代码)是一种严重的气味,应始终将其最小化。 仅仅因为Slim使您可以用大量的逻辑来填充模板,这并不意味着您应该这样做。 在那个部门练习约束! 另一方面,做得对,Slim使在需要的地方注入Ruby变得非常优雅。

内联HTML

如果您需要在Slim模板中编写HTML,则可以选择。 我没有使用过该功能,也不想使用它,但是也许在过渡阶段,这可能对新手很有帮助。 让我们快速浏览一下。

doctype html
<html>
  head
    title = full_title(yield(:title))
    = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true
    = javascript_include_tag 'application', 'data-turbolinks-track' => true
    = csrf_meta_tags
  <body>
    header.navbar
      .logo
        = link_to "sample app", 'root_path', id: "logo"
        <nav>
          ul.navbar-right
            li
              = link_to "Home",   'root_path'
            li
              = link_to "Help",   'help_path'
            li
              = link_to "Log in", 'login_path'
        </nav>
    .main
      = yield
  </body>
</html>

当Slim遇到左尖括号< ,它知道您要混合一些HTML。

逐字记录文字(逐字逐句)

管道字符| 向Slim发出信号,表示您希望使用纯文本(逐词),然后仅复制行。 实际上,这使您避免了任何类型的处理。 该文档说,如果要在多行上写逐字记录文本,则必须在每个换行符之间缩进文本。

body
  p
    | 
      Slim is my new best friend. Slim is my new best friend.
HTML输出
<body>
  <p>
    Slim is my new best friend. Slim is my new best friend.
  </p>
</body>

屏幕截图

Screenshot of the templates output

如果将文本与竖线字符放在同一行,则可以在竖线后加上一个空格来设置左边距。 出于好奇,我愚弄了一下,发现了以下结果。 只有最后一个示例变体有一些明显的打you,您应该注意-它吞没了句子的第一个单词。

body
  p
    | 
      This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
            And so on...

  p
    | This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
            And so on...

  p This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
            And so on...

  p This line is on the left margin.
    This line will have one space in front of it.
    This line will have two spaces in front of it.
    And so on...

  p
    This line is on the left margin.
    This line will have one space in front of it.
    This line will have two spaces in front of it.
    And so on...

屏幕截图

Screenshot of the output by the above source code

将输出呈现到HTML标记中的方式有​​所不同。

<body>
    <p>
      This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
            And so on...
    </p>

    <p>
      This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
           And so on...
    </p>

    <p>
      This line is on the left margin.
         This line will have one space in front of it.
           This line will have two spaces in front of it.
             And so on...
    </p>

    <p>
      This line is on the left margin.
      This line will have one space in front of it.
      This line will have two spaces in front of it.
      And so on...
    </p>

    <p>
      <This>line is on the left margin.</This><This>line will have one space in front of it.</This><This>line will have two spaces in front of it.</This><And>so on...</And>
    </p>
  </body>

注释

当然,有必要不时地注释掉您的代码。 但是,请不要忘记,太多的评论也是一种味道。 只要尽量将其保持在最低水平即可!

您只需注释掉任何代码就可以使用正斜杠/

body
  /p
    | This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
           And so on...

繁荣! 现在,此段已从页面中删除。 此注释在最终HTML标记中没有任何痕迹。 您只需要将其应用于父选择器,它的所有子选择器也会被注释掉。 因此,即使是评论也很苗条且最少。

另一方面,如果您想要一些HTML注释<!-- -->出现在最终呈现的输出中,则只需添加一个感叹号! 斜线之后。

body
  /!p
    | This line is on the left margin.
       This line will have one space in front of it.
         This line will have two spaces in front of it.
           And so on...
HTML输出
<body>
  <!--p
      | This line is on the left margin.
        This line will have one space in front of it.
          This line will have two spaces in front of it.
            And so on...-->

整齐!

自定义快捷方式

我们一直都在使用快捷方式。 当您键入一个点. 或井号( #您告诉Slim您想对类和ID使用预定义的快捷方式。 当然,这是一个非常好的默认值,但是您可以做些什么来扩展它并创建自己的小片段代码段? 我们可以对标签和属性都这样做。 欢迎来到Slim的绝妙!

在Rails中,我们只需要使用以下模式设置一个初始化程序:

config / initializers / slim.rb
Slim::Engine.set_options shortcut: {'c' => {tag: 'container'}, '#' => {attr: 'id'}, '.' => {attr: 'class'} }

在Sinatra应用程序中,您只需在require 'slim'的行下方的任何位置添加相同的配置。

your_sinatra_app.rb

require 'sinatra'
require 'slim'

Slim::Engine.set_options shortcut: {'c' => {tag: 'container'}, '#' => {attr: 'id'}, '.' => {attr: 'class'} }

get('/') { slim :index }

__END__

@@ index
doctype html
html
  head
    title Slim Templates
    body
      h1 Boss Level Templates With Slim

您可以在Slim :: Engine上设置选项,方法是提供带有所需快捷方式的哈希值。 在上面的示例中,我们指示Slim将c用作container标签的快捷方式。 您可以在Slim文件中像这样使用它:

c.content Now you have a container tag with a .content class.

当然,呈现HTML将如下所示:

HTML
<container class="content">
  Now you have a container tag with a .content class.
</container>

很好,是吗? 但是您不认为那是音乐停止的地方,对吗? 我们可以做得更多。 让我给你一个例子,它涉及更多:

config / initializers / slim.rb
Slim::Engine.set_options shortcut: {
            '#' => {attr: 'id'},
            '.' => {attr: 'class'},
            'c' => {tag: 'container'},
            '&' => {tag: 'input', attr: 'type'}, 
            '@' => {attr: 'role'},
            '^' => {attr: %w(data-role role)}
           }

在此示例中,我不仅创建了自定义标签,还提供了方便的自定义属性。 让我们逐步剖析。 顺便说一句,我将options散列分成几行,以保持可读性,并避免有一长串没人喜欢的代码。 读起来好多了,你不觉得吗?

通过连字符& ,我们现在可以创建一个输入标签,我们只是需要给它一个类型直接跟随符号。 我们可以使用任何有意义的符号。 无需使用与我相同的方法。 但是要小心,并尝试在该部门做出毫不妥协的决定。

&text name="user"
&password name="pw"
&submit
HTML输出
<input name="user" type="text">
<input name="pw" type="password">
<input type="submit">

使用自定义快捷方式对此初始化程序进行更改时,请不要忘记重启本地服务器。 否则,您的更改将不会在预处理过程中反映出来。

接下来,如果需要role属性,现在可以在其前面加上@符号。

.person@admin Daniel Mendler
HTML输出
<div class="person" role="admin">
  Daniel Mendler
</div>

刷新:角色属性是一种语义方法,用于描述所讨论元素的角色-如果需要确定元素的用途。

看到,通过点我们得到一个class="person"类, @admin role="admin"给了我们一个role="admin" 。 很好用的花花公子,但我们可以更进一步,并使用数组指定应通过单个快捷方式创建的多个属性。

.nifty^hacker CrackDoctor
HTML输出
<div class="nifty" data-role="hacker" role="hacker">
  CrackDoctor
</div>

因为我们为^快捷方式关联了属性数组,所以Slim通过单个符号同时创建了data-rolerole属性。 那可以很方便。 想象一下,如果您要输出类似于以下内容的元素,并且可以使用快捷方式和一些Ruby代码来简洁地实现它。

HTML
<source src="track1.mp3" type="audio/mpeg" data-duration="1min5secs" data-tempo="125bpm" data-artist="The Beatles" />

手工编写所有这些内容似乎并不是您时间的最佳利用,因为我们有代码可以为我们完成这项工作。 好了,您所拥有的就是创建自己的一组很棒的快捷键所需要的全部知识,或者在您不作任何限制的情况下创建一个烂摊子。 我建议您不要太着急了,特别是不要尝试定义使用已经附加了Slim的符号的快捷方式。

刷新:data-属性用于在页面或应用程序上包含一些私有数据。 例如,可帮助您过滤内容的资料。 它们是可以在所有HTML元素上使用的自定义属性。 将它们用于JavaScript是另一种常见的做法。 如果要确保显示特定元素并且要避免让设计师弄乱您的样式,这对于测试页面上的元素也非常方便。

配置苗条

在您离开之前,我想向您简要介绍一下广泛的配置选项以及如何应用它们。 对于Rails,您将创建一个环境文件,如config/environments/development.rb并指定所需的选项。 您只需将配置放在Rails.application.configure块中的某个位置Rails.application.configure

Rails.application.configure do
  Slim::Engine.set_options default_tag: 'p', 
                           tabsize: 2, 
                           attr_list_delims: {'(' => ')', 
                                              '[' => ']',
                                              '{' => '}', 
                                              '«' => '»', 
                                              '‹' => '›'
                                              }
end

在此配置中,我确保如果省略标签名称,则创建的默认标签是<p>标签,而不是div标签,这是标准设置。 另外,我将tabsize调整为使用两个空格,最后添加了两个定界符来包装标签的属性。 现在,我也可以使用‹ ›« » 。 并不是非常有用,但可以用于演示目的。

在下面的示例中,您可以看到属性包装器的所有定界符都会创建相同的输出,而且.some-class#some-id会默认创建<p>标记。

body
  #zeroth
  a{href="http://slim-lang.com" title='Home page'} Goto the home page

  .first
  a[href="http://slim-lang.com" title='Home page'] Goto the home page

  .second
  a(href="http://slim-lang.com" title='Home page') Goto the home page

  .third
  a‹href="http://slim-lang.com" title='Home page'› Goto the home page

  .fourth
  a«href="http://slim-lang.com" title='Home page'» Goto the home page
HTML输出
<body>
    <p id="zeroth"></p>
    <a href="http://slim-lang.com" title="Home page">Goto the home page</a>

    <p class="first"></p>
    <a href="http://slim-lang.com" title="Home page">Goto the home page</a>

    <p class="second"></p>
    <a href="http://slim-lang.com" title="Home page">Goto the home page</a>

    <p class="third"></p>
    <a href="http://slim-lang.com" title="Home page">Goto the home page</a>

    <p class="fourth"></p>
    <a href="http://slim-lang.com" title="Home page">Goto the home page</a>
</body>

另外,您也可以在config/initializers/slim.rb设置这些内容,如我在有关自定义快捷方式的部分中所展示的。

对于Sinatra,这与快捷方式部分中讨论的钻探相同。 只需在您的require 'slim'语句下方的某个位置设置选项,就可以了。

查看“可用选项”下的文档 ,以了解有关可用于配置的内容的更多信息。 Slim为您提供许多选择。

最后的想法

基本上就是这样。 如果需要,您还应该深入研究一两个以上的高级主题,但我认为这些主题通常不适合初学者使用,也不是日常使用的重点。 我想保持简单,并向您展示快速切换到这个很棒的模板引擎所需要的一切。 玩得开心,我希望Slim现在是您最喜欢的新玩具之一!

翻译自: https://code.tutsplus.com/articles/ruby-templating-with-slim-part-2--cms-26094

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值