【初心者むけ】slim記法
最近脚がものすごく強くなっていること23期インナーサイ79kg挙がるです。
現場ではslimが使われているからslimを使おうと現場railsに書いてあったことを思い出したので、今回はslim記法に関して学習していきたいと思います。
slimとは
https://github.com/slim-template/slim
早速書き方を覗いてみる。
<div></div>
<html></html>
<meta></meta>
<header></header>
<footer></footer>
<table></table>
<h1></h1>
<p></p>
<a><a>
<ul></ul>
<li></li>
上記のerb記法は、下記のように、<>を無くしてスリムに書く事ができる。
div
html
meta
header
footer
table
h1
p
a
ul
li
slim公式に書いてあった下記記述例を読み解きながらslimに慣れていきたい。
html
head
title Slim Examples
meta name="keywords" content="template language"meta name="author" content=author
link rel="icon" type="image/png" href=file_path("favicon.png")
javascript:
alert('Slim supports embedded javascript!')
body
h1 Markup examples
#content
p This example shows you how a basic Slim file looks.
== yield
- if items.any?
table#items
- for item in items
tr
td.name = item.name
td.price = item.price
- else
p No items found. Please add some inventory.
Thank you!
div id="footer"
== render 'footer'
| Copyright © #{@year} #{@author}
上から読み解いていく。
#slim
html
head
title Slim Examples
meta name="keywords" content="template language"meta name="author" content=author
#erb
<html>
<head>
<title> Slim Examples</title>
<meta name="keywords" content="template language"meta name="author" content=author />
</head>
</html>
インデントを一つ間違えるだけでエラーになってしまう。
<aside> 💡 slimはインデントに厳しい
</aside>
link
#slim
link rel="icon" type="image/png" href=file_path("favicon.png")
#erb
<a link rel="icon" type="image/png" href=file_path("favicon.png")>
javascript
javascript:
alert('Slim supports embedded javascript!')
<script>
alert('Slim supports embedded javascript!')
</script>
id
#content
p This example shows you how a basic Slim file looks.
<p id="content">This example shows you how a basic Slim file looks.</p>
Rubyコード
== yield
<%= yield %>
if文
#slim
- if items.any?
table#items
- for item in items
tr
td.name = item.name
td.price = item.price
- else
p No items found. Please add some inventory.
Thank you!
#erb
<% if items.any?>
<table id="items">
<%for item in items %>
<tr>
<td class="name"><%=item.name%>
<td class="price"><%=item.price%>
<% else%>
<p>No items found. Please add some inventory.Thank you!</p>
<%end%>
|
#slim
div id="footer"
== render 'footer'
| Copyright © #{@year} #{@author}
#erb
<div id="footer">
<%=render 'footer'%>
Copyright ©#{@year} #{@author}
</div>
まとめ
・<>がいらない
・テキストは |の後ろにかく。
・if → -
・<%= %> → =
・<% %> → -
・コメント → /
・id指定 → #
・class指定 → .