Add lang to get_taxonomy & get_taxonomy_url

This commit is contained in:
Vincent Prouillet 2019-08-15 22:14:53 +02:00
parent 6d5611f409
commit 6a7e955ab0
7 changed files with 78 additions and 20 deletions

View File

@ -17,6 +17,8 @@
- Taxonomies can now have the same name in multiple languages - Taxonomies can now have the same name in multiple languages
- `zola init` can now be create sites inside the current directory - `zola init` can now be create sites inside the current directory
- Fix table of contents generation for deep heading levels - Fix table of contents generation for deep heading levels
- Add `lang` in all templates context except sitemap, robots etc
- Add `lang` parameter to `get_taxonomy` and `get_taxonomy_url`
## 0.8.0 (2019-06-22) ## 0.8.0 (2019-06-22)

View File

@ -211,10 +211,12 @@ impl<'a> Paginator<'a> {
PaginationRoot::Section(s) => { PaginationRoot::Section(s) => {
context context
.insert("section", &SerializingSection::from_section_basic(s, Some(library))); .insert("section", &SerializingSection::from_section_basic(s, Some(library)));
context.insert("lang", &s.lang);
} }
PaginationRoot::Taxonomy(t, item) => { PaginationRoot::Taxonomy(t, item) => {
context.insert("taxonomy", &t.kind); context.insert("taxonomy", &t.kind);
context.insert("term", &item.serialize(library)); context.insert("term", &item.serialize(library));
context.insert("lang", &t.kind.lang);
} }
}; };
context.insert("current_url", &pager.permalink); context.insert("current_url", &pager.permalink);

View File

@ -169,6 +169,7 @@ impl Taxonomy {
self.items.iter().map(|i| SerializedTaxonomyItem::from_item(i, library)).collect(); self.items.iter().map(|i| SerializedTaxonomyItem::from_item(i, library)).collect();
context.insert("terms", &terms); context.insert("terms", &terms);
context.insert("taxonomy", &self.kind); context.insert("taxonomy", &self.kind);
context.insert("lang", &self.kind.lang);
context.insert("current_url", &config.make_permalink(&self.kind.name)); context.insert("current_url", &config.make_permalink(&self.kind.name));
context.insert("current_path", &self.kind.name); context.insert("current_path", &self.kind.name);

View File

@ -525,7 +525,7 @@ impl Site {
self.tera.register_function("trans", global_fns::Trans::new(self.config.clone())); self.tera.register_function("trans", global_fns::Trans::new(self.config.clone()));
self.tera.register_function( self.tera.register_function(
"get_taxonomy_url", "get_taxonomy_url",
global_fns::GetTaxonomyUrl::new(&self.taxonomies), global_fns::GetTaxonomyUrl::new(&self.config.default_language,&self.taxonomies),
); );
} }
@ -540,7 +540,7 @@ impl Site {
); );
self.tera.register_function( self.tera.register_function(
"get_taxonomy", "get_taxonomy",
global_fns::GetTaxonomy::new(self.taxonomies.clone(), self.library.clone()), global_fns::GetTaxonomy::new(&self.config.default_language, self.taxonomies.clone(), self.library.clone()),
); );
} }

View File

@ -176,18 +176,19 @@ impl TeraFn for GetImageMeta {
#[derive(Debug)] #[derive(Debug)]
pub struct GetTaxonomyUrl { pub struct GetTaxonomyUrl {
taxonomies: HashMap<String, HashMap<String, String>>, taxonomies: HashMap<String, HashMap<String, String>>,
default_lang: String,
} }
impl GetTaxonomyUrl { impl GetTaxonomyUrl {
pub fn new(all_taxonomies: &[Taxonomy]) -> Self { pub fn new(default_lang: &str, all_taxonomies: &[Taxonomy]) -> Self {
let mut taxonomies = HashMap::new(); let mut taxonomies = HashMap::new();
for taxonomy in all_taxonomies { for taxo in all_taxonomies {
let mut items = HashMap::new(); let mut items = HashMap::new();
for item in &taxonomy.items { for item in &taxo.items {
items.insert(item.name.clone(), item.permalink.clone()); items.insert(item.name.clone(), item.permalink.clone());
} }
taxonomies.insert(taxonomy.kind.name.clone(), items); taxonomies.insert(format!("{}-{}", taxo.kind.name, taxo.kind.lang), items);
} }
Self { taxonomies } Self { taxonomies, default_lang: default_lang.to_string() }
} }
} }
impl TeraFn for GetTaxonomyUrl { impl TeraFn for GetTaxonomyUrl {
@ -202,7 +203,10 @@ impl TeraFn for GetTaxonomyUrl {
args.get("name"), args.get("name"),
"`get_taxonomy_url` requires a `name` argument with a string value" "`get_taxonomy_url` requires a `name` argument with a string value"
); );
let container = match self.taxonomies.get(&kind) { let lang = optional_arg!(String, args.get("lang"), "`get_taxonomy`: `lang` must be a string")
.unwrap_or_else(|| self.default_lang.clone());
let container = match self.taxonomies.get(&format!("{}-{}", kind, lang)) {
Some(c) => c, Some(c) => c,
None => { None => {
return Err(format!( return Err(format!(
@ -289,14 +293,15 @@ impl TeraFn for GetSection {
pub struct GetTaxonomy { pub struct GetTaxonomy {
library: Arc<RwLock<Library>>, library: Arc<RwLock<Library>>,
taxonomies: HashMap<String, Taxonomy>, taxonomies: HashMap<String, Taxonomy>,
default_lang: String,
} }
impl GetTaxonomy { impl GetTaxonomy {
pub fn new(all_taxonomies: Vec<Taxonomy>, library: Arc<RwLock<Library>>) -> Self { pub fn new(default_lang: &str, all_taxonomies: Vec<Taxonomy>, library: Arc<RwLock<Library>>) -> Self {
let mut taxonomies = HashMap::new(); let mut taxonomies = HashMap::new();
for taxo in all_taxonomies { for taxo in all_taxonomies {
taxonomies.insert(taxo.kind.name.clone(), taxo); taxonomies.insert(format!("{}-{}", taxo.kind.name, taxo.kind.lang), taxo);
} }
Self { taxonomies, library } Self { taxonomies, library, default_lang: default_lang.to_string() }
} }
} }
impl TeraFn for GetTaxonomy { impl TeraFn for GetTaxonomy {
@ -307,7 +312,10 @@ impl TeraFn for GetTaxonomy {
"`get_taxonomy` requires a `kind` argument with a string value" "`get_taxonomy` requires a `kind` argument with a string value"
); );
match self.taxonomies.get(&kind) { let lang = optional_arg!(String, args.get("lang"), "`get_taxonomy`: `lang` must be a string")
.unwrap_or_else(|| self.default_lang.clone());
match self.taxonomies.get(&format!("{}-{}", kind, lang)) {
Some(t) => Ok(to_value(t.to_serialized(&self.library.read().unwrap())).unwrap()), Some(t) => Ok(to_value(t.to_serialized(&self.library.read().unwrap())).unwrap()),
None => { None => {
Err(format!("`get_taxonomy` received an unknown taxonomy as kind: {}", kind).into()) Err(format!("`get_taxonomy` received an unknown taxonomy as kind: {}", kind).into())
@ -376,6 +384,11 @@ mod tests {
lang: config.default_language.clone(), lang: config.default_language.clone(),
..TaxonomyConfig::default() ..TaxonomyConfig::default()
}; };
let taxo_config_fr = TaxonomyConfig {
name: "tags".to_string(),
lang: "fr".to_string(),
..TaxonomyConfig::default()
};
let library = Arc::new(RwLock::new(Library::new(0, 0, false))); let library = Arc::new(RwLock::new(Library::new(0, 0, false)));
let tag = TaxonomyItem::new( let tag = TaxonomyItem::new(
"Programming", "Programming",
@ -384,10 +397,19 @@ mod tests {
vec![], vec![],
&library.read().unwrap(), &library.read().unwrap(),
); );
let tag_fr = TaxonomyItem::new(
"Programmation",
&taxo_config_fr,
&config,
vec![],
&library.read().unwrap(),
);
let tags = Taxonomy { kind: taxo_config, items: vec![tag] }; let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
let tags_fr = Taxonomy { kind: taxo_config_fr, items: vec![tag_fr] };
let taxonomies = vec![tags.clone()]; let taxonomies = vec![tags.clone(), tags_fr.clone()];
let static_fn = GetTaxonomy::new(taxonomies.clone(), library.clone()); let static_fn = GetTaxonomy::new(&config.default_language, taxonomies.clone(), library.clone())
;
// can find it correctly // can find it correctly
let mut args = HashMap::new(); let mut args = HashMap::new();
args.insert("kind".to_string(), to_value("tags").unwrap()); args.insert("kind".to_string(), to_value("tags").unwrap());
@ -412,6 +434,19 @@ mod tests {
res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["pages"], res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["pages"],
Value::Array(vec![]) Value::Array(vec![])
); );
// Works with other languages as well
let mut args = HashMap::new();
args.insert("kind".to_string(), to_value("tags").unwrap());
args.insert("lang".to_string(), to_value("fr").unwrap());
let res = static_fn.call(&args).unwrap();
let res_obj = res.as_object().unwrap();
assert_eq!(res_obj["kind"], to_value(tags_fr.kind).unwrap());
assert_eq!(res_obj["items"].clone().as_array().unwrap().len(), 1);
assert_eq!(
res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["name"],
Value::String("Programmation".to_string())
);
// and errors if it can't find it // and errors if it can't find it
let mut args = HashMap::new(); let mut args = HashMap::new();
args.insert("kind".to_string(), to_value("something-else").unwrap()); args.insert("kind".to_string(), to_value("something-else").unwrap());
@ -426,12 +461,19 @@ mod tests {
lang: config.default_language.clone(), lang: config.default_language.clone(),
..TaxonomyConfig::default() ..TaxonomyConfig::default()
}; };
let taxo_config_fr = TaxonomyConfig {
name: "tags".to_string(),
lang: "fr".to_string(),
..TaxonomyConfig::default()
};
let library = Library::new(0, 0, false); let library = Library::new(0, 0, false);
let tag = TaxonomyItem::new("Programming", &taxo_config, &config, vec![], &library); let tag = TaxonomyItem::new("Programming", &taxo_config, &config, vec![], &library);
let tag_fr = TaxonomyItem::new("Programmation", &taxo_config_fr, &config, vec![], &library);
let tags = Taxonomy { kind: taxo_config, items: vec![tag] }; let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
let tags_fr = Taxonomy { kind: taxo_config_fr, items: vec![tag_fr] };
let taxonomies = vec![tags.clone()]; let taxonomies = vec![tags.clone(), tags_fr.clone()];
let static_fn = GetTaxonomyUrl::new(&taxonomies); let static_fn = GetTaxonomyUrl::new(&config.default_language, &taxonomies);
// can find it correctly // can find it correctly
let mut args = HashMap::new(); let mut args = HashMap::new();
args.insert("kind".to_string(), to_value("tags").unwrap()); args.insert("kind".to_string(), to_value("tags").unwrap());
@ -440,6 +482,16 @@ mod tests {
static_fn.call(&args).unwrap(), static_fn.call(&args).unwrap(),
to_value("http://a-website.com/tags/programming/").unwrap() to_value("http://a-website.com/tags/programming/").unwrap()
); );
// works with other languages
let mut args = HashMap::new();
args.insert("kind".to_string(), to_value("tags").unwrap());
args.insert("name".to_string(), to_value("Programmation").unwrap());
args.insert("lang".to_string(), to_value("fr").unwrap());
assert_eq!(
static_fn.call(&args).unwrap(),
to_value("http://a-website.com/fr/tags/programmation/").unwrap()
);
// and errors if it can't find it // and errors if it can't find it
let mut args = HashMap::new(); let mut args = HashMap::new();
args.insert("kind".to_string(), to_value("tags").unwrap()); args.insert("kind".to_string(), to_value("tags").unwrap());

View File

@ -5,10 +5,8 @@ weight = 30
Two things can get paginated: a section and a taxonomy term. Two things can get paginated: a section and a taxonomy term.
A paginated section gets the same `section` variable as a normal Both kinds get a `paginator` variable of the `Pager` type, on top of the common variables mentioned in the
[section page](@/documentation/templates/pages-sections.md#section-variables) minus its pages [overview page](@/documentation/templates/overview.md):
while both a paginated taxonomy page and a paginated section page gets a
`paginator` variable of the `Pager` type:
```ts ```ts
// How many items per pager // How many items per pager

View File

@ -6,3 +6,6 @@ Language: {{lang}}
Translated in {{t.lang|default(value=config.default_language)}}: {{t.title}} {{t.permalink|safe}} Translated in {{t.lang|default(value=config.default_language)}}: {{t.title}} {{t.permalink|safe}}
{% endfor %} {% endfor %}
{% for taxo_kind, items in page.taxonomies %}
{% set taxo = get_taxonomy(kind=taxo_kind, lang=lang) %}
{% endfor %}