kainjow / Mustache

Mustache text templates for modern C++
Boost Software License 1.0
357 stars 49 forks source link

wrong render result for section #35

Closed yangqinj closed 5 years ago

yangqinj commented 5 years ago

Here I have a template with a section

static const char* temp =  R"(
{{#path_handlers}}
 <li><a class="nav-link"href="{{path}}">{{alias}}</a></li>
{{/path_handlers}}
)";

To render this template, I use the following code to fill the tag:

  data data_path_alias{data::type::list};
  data_path_alias << data{"path", "/"} << data{"alias", "Home"};
  data_path_alias << data{"path", "/config"} << data{"alias", "Configuration"};
  data data_path_handlers{"path_handlers", data_path_alias};

  using mycontext = context<mustache::string_type>;
  mycontext ctx;
  ctx.push(&data_path_handlers);

  cout << tmpl.render(ctx) << endl;

The resulting output is:

<li><a class="nav-link"href="/"></a></li>

 <li><a class="nav-link"href="">Home</a></li>

 <li><a class="nav-link"href="/config"></a></li>

 <li><a class="nav-link"href="">Configuration</a></li>

There two wrong points:

Did I wrongly use the data with data::type::list?

kainjow commented 5 years ago

Sorry for the delay. My email was broken :)

What version are you using?

kainjow commented 5 years ago

So looking at this again, yes, you're adding 4 items to the list, so it's:

1: data{"path", "/"} 2: data{"alias", "Home"} 3: data{"path", "/config"} 4: data{"alias", "Configuration"}

You need to use objects (unordered maps). There are some examples in the tests: https://github.com/kainjow/Mustache/blob/master/tests.cpp#L993

Also you shouldn't need to use the context class directly, just pass data_path_handlers to render instead.