理解してる人は簡単にできるのかもしれないけど、出来るようになるまでに時間かかった(そしてググっても出てこなかった)ので記録として残しておきます。
ruby+sinatra+slimで変数を使ってcssを定義する方法です。
app.rb
get "/test" do raw_data = [ "Dallas, USA", "Tokyo, Japan", "Munich, Germany", ] @css = { "th": ["background-color", "#bde9ba"] } @results = {} raw_data.each do |item| city, country = item.split(/, \s* /x) @results[city] = country end slim :test, :layout => :csstest end
csstest.slim
doctype html html head meta charset='utf-8' link rel="stylesheet" type="text/css" href="/css/input.css" -@css.each do |k, v| css: #{k} {#{v[0]}: #{v[1]}} body h1 This is the Layout. == yield
test.slim
table thead tr th City th Country tbody - @results.each do |city, country| tr td = city td = country
csstest.slimの
-@css.each do |k, v| css:
ここの順番が逆だとエラーになってうまく行きませんでした。
これを応用していけば、データベースのデータをカード化して表示するときにいろいろ便利に書けるはず…
例題の中身は、MySQLのRuby Sinatraテーブル-スタックオーバーフロー https://stackoverflow.com/questions/30929545/ruby-sinatra-table-from-mysql
こちらを使わせてもらいました。