如何改进这个Enlive模板?

时间:2012-12-29 14:48:56

标签: clojure enlive

我使用此Enlive模板将其下方的HTML转换为下面的HTML。基于一组推特名称,我生成一个带链接的表。如何摆脱enlive/clone-for内的打嗝?

(enlive/deftemplate usernames-table-body
  "public/whoisnotfollowingme.html"
  [usernames]
  [:table.names :tbody :tr]
  (enlive/clone-for [username usernames]
                    [:td]
                    (enlive/html-content
                     (html [:a {:href (str "https://twitter.com/intent/user?screen_name=" username)} username]))))

HTML输入

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="/bootstrap/css/bootstrap.css"/>
  </head>
  <body>
    <script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
    <div class="container">
      <div class="hero-unit">
        <p class="names">These people who you are following are not following you back!</p>
      </div>
      <table class="names table table-striped">
        <thead>
          <tr>
            <th>Username</th>
          </tr>
          </thead>
          <tbody>
            <tr>
              <td>name</td>
            </tr>
          </tbody>
      </table>
    </div>
  </body>
</html>

HTML输出

<html> 
   <head>
    <link href="/bootstrap/css/bootstrap.css" rel="stylesheet" />
  </head> 
   <body> 
     <script src="//platform.twitter.com/widgets.js" type="text/javascript"></script> 
     <div class="container"> 
       <div class="hero-unit">
        <p class="names">These people who you are following are not following you back!</p>
      </div> 
       <table class="names table table-striped"> 
         <thead>
          <tr>
            <th>Username</th>
          </tr>
          </thead> 
           <tbody> 
             <tr> 
               <td> < a   href =" https://twitter.com/intent/user?screen_name=foo " > foo </ a > </td> 
             </tr> <tr> 
               <td> < a   href =" https://twitter.com/intent/user?screen_name=bar " > bar </ a > </td> 
             </tr> 
           </tbody> 
       </table> 
     </div> 
   </body> 

 </html>

1 个答案:

答案 0 :(得分:1)

您可以从以下位置更改tbody.tr模板:

<tr>
  <td>name</td>
</tr>

为:

<tr>
  <td><a href="https://twitter.com/intent/user?screen_name=foo">foo</a></td>
</tr>

现在,您的HTML资源是您想要的输出的一个工作示例。

然后修改你的deftemplate以支持它:

(enlive/deftemplate usernames-table-body
  "public/whoisnotfollowingme.html"
  [usernames]

  [:table.names :tbody :tr]
  (enlive/clone-for [username usernames]
                    [:td :a]
                    (enlive/do->
                     (enlive/set-attr :href (str "https://twitter.com/intent/user?screen_name=" username))
                     (enlive/content username))))

编辑:如果您想删除代码中的URL,请尝试将您的href更改为?screen_name =然后将代码修改为:

                    (enlive/do->
                     (fn [node] (update-in node [:attrs :href] #(str % username)))
                     (enlive/content username))))

您也可以使用它。参见例如Append to an attribute in Enlive