Evolutio
Evolutio

Reputation: 974

Ruby how to display a json in haml

I'm new to ruby and i want to parse a json-File to haml.

my idea was to parse a jsonarray:

{
    "theme": "default",
    "metatags":{
        "title":"Test",
        "charset":"utf-8"
    },
    "body":{
        "p":{
            "class": "test",
            "text": "P"
        },
        "div": "DIV",
        "span": "SPAN"
    }
}

to a haml file. With the json code i want to display my htmlfile:

<body>
<p class="text">P</p>
<div>DIV</div>
<span>SPAN</span>
</body>

my app.rb looks like this:

require 'sinatra'
require 'json_builder'

file = open('configs/evolutio.json')
json = file.read
user_settings = JSON.parse(json)

set :user_settings, user_settings

get '/' do
    @body = user_settings["body"]
    haml :"templates/#{user_settings["theme"]}/index"
end

and my index.haml like this:

%html
    %head
        %title #{options.user_settings["metatags"]["title"]}
        %meta{'http-equiv' => 'Content-Type', :content => 'text/html'}
        %meta{'charset' => options.user_settings["metatags"]["charset"]}
    %body
        - cnt = 1
        - @body.each do |tag|
            #{tag.inspect} <br>
            - haml_tag tag[0], tag[1]

my html code looks like this:

<html>
  <head>
    <title>Test</title>
    <meta content='text/html' http-equiv='Content-Type'>
    <meta charset='utf-8'>
  </head>
  <body>
    ["p", {"class"=>"test", "text"=>"P"}] <br>
    <p class='test' text='P'></p>
    ["div", "DIV"] <br>
    <div>DIV</div>
    ["span", "SPAN"] <br>
    <span>SPAN</span>
  </body>
</html>

Upvotes: 0

Views: 3849

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

According to the documentation, if you want to have text and attributes, you need to separate the two. something like this should work:

%html
    %head
        %title #{options.user_settings["metatags"]["title"]}
        %meta{'http-equiv' => 'Content-Type', :content => 'text/html'}
        %meta{'charset' => options.user_settings["metatags"]["charset"]}
    %body
        - cnt = 1
        - @body.each do |name, text|
            if text.is_a?(Hash)
              attr, text = text, text.delete('text')
              - haml_tag name, text, attr
            else
              - haml_tag name, text

Upvotes: 2

Related Questions