Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Yajl layouts? #145

Closed
jamiehodge opened this Issue · 5 comments

4 participants

@jamiehodge

I'm using yajl templates via Sinatra and would like to use it as a layout, yielding to nested yajl templates. Would someone please help show me how this could be done? I assume the json object needs to be passed to each respective sub-template for amendments.

Best,

Jamie

@rkh
Collaborator

@weppos you wanna jump in here?

@weppos

I honestly never tried to use it with a template. However, Yajl templates are very similar to Builder templates except that the content is stored in the JSON variable.

As far as I remember, you should be able to place a yield call in a template and Sinatra will execute the content of the view and merge it into the template. I was trying to find an action + template example using Builder XML, but I can't find one.

# the layout
json = {
  :foo => "bar",
  :baz => yield,
}

# the action
{
  :hello => "world"
}

# the result
json = {
  :foo => "bar",
  :baz => {
    :hello => "world"
  },
}
@jamiehodge

Here is a typical scenario. The problem being that a string is yielded by :test. The only way I can see getting around this is actually passing the json object to :test from :layout and then modifying the json object on return.

require 'sinatra'
require 'yajl'

get '/' do
  yajl :test
end

 __END__
@@layout
json = {
  foo: 'bar',
  baz: yield
}

@@test
json = {
  biz: 'buzz'
}

# => {"foo":"bar","baz":"{\"biz\":\"buzz\"}"}
@weppos

This is a case I haven't considered when I wrote the engine. I'll try to have it a look but I'm in a middle of a very busy period and I don't expect to be able to work on it soon.

@judofyr
Collaborator

You can use this helper method/class:

require 'sinatra'
require 'yajl'

WrappedJSON = Struct.new(:object) do
  def to_json
    object
  end
end

helpers do
  def wrap_json(obj)
    WrappedJSON.new(obj)
  end
end

get '/' do
  yajl :test
end

__END__

@@layout
json = {
  foo: 'bar',
  baz: wrap_json(yield)
}

@@test
json = {
  biz: 'buzz'
}
@judofyr judofyr closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.