Fractal mustache in ruby

I tried to display a mustache pattern that references it. But this gives the error "The stack level is too deep."

Here is my ruby ​​code.

The following code snippet is in person.rb

require 'mustache' require 'active_support' str = File.read("person.json") j = ActiveSupport::JSON.decode(str) Mustache.template_file = "person.mustache" puts Mustache.render(j) 

The following json content is in person.json

 { "name":"Jason", "rels":[ {"type":"friend", "ref":{ "name":"John", "rels":[ {"type":"friend", "ref":{"name":"Chrissy"}} ] }}, {"type":"family", "ref":{"name":"Owen"}} ] } 

The following file is in the person.mustache file

 {{#rels}} <ul> <li>Type: {{type}}</li> {{#ref}} {{> person}} {{/ref}} </ul> {{/rels}} 

Can someone point me in the right direction?

+4
source share
1 answer

From the exact guide :

Partials
[...]
They also inherit the calling context. If in ERB it could be:

 <%= partial :next_more, :start => start, :size => size %> 

Mustache only requires this:

 {{> next_more}} 

Why? Since the file next_more.mustache inherits the size and start methods from the calling context.

So, if there are no rels in the current context:

  "ref": { "name": "Chrissy" } 

then you inherit rels from the parent. This gives you a partial rels reference to the parent, which activates the partial rels again, which refers to rels to the parent, which continues until you finish the stack.

If you are going to create a recursive template as follows:

 {{#rels}} <ul> <li>Type: {{type}}</li> {{#ref}} {{> person}} {{/ref}} </ul> {{/rels}} 

then you need to have complete objects at each level:

 { "name":"Jason", "rels":[ {"type":"friend", "ref":{ "name":"John", "rels":[ {"type":"friend", "ref":{"name":"Chrissy","rels":[]}} // <--- rels here ] }}, {"type":"family", "ref":{"name":"Owen","rels":[]}} // <-------------- and here ] } 

You can program your data in JSON or after parsing it, I would recommend that you decompose it after parsing.

+5
source

Source: https://habr.com/ru/post/1435379/


All Articles