Skip to content

Support for vector of structs? #305

@jmafc

Description

@jmafc

I'm trying out inja on something akin to a blog where you may find something like the following (in Python):

posts = [{'id': 1, 'title': 'First', 'body': 'This is one'}, {'id': 2, 'title': 'Second', 'body': 'This is another'}, {'id': 3, 'title': 'Third', 'body': 'One more'}]

I haven't tried it with Jinja2, but I believe this is handled fine, and also even if the items were constructed using a Python class rather than hard-coded dicts.
In C++ the obvious analog is to define a std::vector<Post>, with Post being a struct with the expected data members.
However, if define a json data variable and then try to assign the posts vector, i.e.,

json data;
data["posts"] = posts;

the compiler complains that no known conversion for argument 1 from ‘std::vector<Post>’ to ‘nlohmann::json_abi_v3_11_3::basic_json<>’.
Is there a simple way to accomplish this? If this isn't quite as easy, would a loop through the posts to fill out each known member, e.g., data[i]["title"] = posts[i].title; be possible, and if so, how can inja deal with it in a template for loop, i.e., one that does for post in posts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions