Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to name elements of a Vec<String>? #42

Open
quat1024 opened this issue Mar 11, 2021 · 2 comments
Open

Is it possible to name elements of a Vec<String>? #42

quat1024 opened this issue Mar 11, 2021 · 2 comments

Comments

@quat1024
Copy link

quat1024 commented Mar 11, 2021

So I'm making a personal blog site (surprise), and I wanted to add post tags. No problem, i'll add a field to my struct real quick.

#[derive(Content)]
pub struct Post {
    //...
    pub tags: Vec<String>
}

Now to make a row of links to each tag. Let's see.

{{#tags}}<a href="/post/tag/{{ ? }}">{{ ? }}</a> {{/tags}}

...I'm not sure how to name each item in the Vec. The section repeats 3 times if there are 3 elements in the Vec, but I don't know how to actually refer to the element, to make the sections different.

I was able to solve it using a tuple struct, just because I can name the field 0, like this.

#[derive(Content)]
pub struct Post {
    //...
    pub tags: Vec<Tag>
}

#[derive(Content, Clone, PartialEq, Eq, Hash, Default, Debug)] //idk im not used to tuple structs
pub struct Tag(String);
{{#tags}}<a href="/post/tag/{{0}}">{{0}}</a> {{/tags}}

I'm a little bummed that I needed a useless tuple struct for this though. Is there a nicer way to do this?

@maciejhirsz
Copy link
Owner

There isn't a way to address "self" in mustache as far as I'm aware, so that was never part of the spec here either. I'd be happy to accept a PR that adds render_field_escaped and render_field_unescaped to String and str impls of Content for a predefined faux field name, such as . (so {{.}} in templates).

@maciejhirsz
Copy link
Owner

Having slept on this, I think the proper way to do it is to expose sections to the same variable name as the main field in the map, so in your case that should be: {{#tags}}<a href="/post/tag/{{tags}}">{{tags}}</a> {{/tags}}.

This would make loops analogous to how a single string works with existence checks. On the flip side, it will require a bit more messing around in the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants