search for nested includes

This commit is contained in:
KitsuneCafe 2024-02-05 17:07:42 -05:00
parent 38e161ae3d
commit 13868747c2
4 changed files with 30 additions and 18 deletions

View file

@ -1,4 +1,8 @@
use std::{path::PathBuf, io::BufReader, fs::{File, read, self}};
use std::{
fs::{self, read, File},
io::BufReader,
path::{Path, PathBuf},
};
use once_cell::sync::Lazy;
use regex::Regex;
@ -42,23 +46,24 @@ impl<'a> TeraParser<'a> {
self.context = Some(context);
}
fn load_template(&mut self, path: &str, src: &[u8]) -> Result<(), tera::Error> {
fn load_template<P: AsRef<Path>>(&mut self, path: &P, src: &[u8]) -> Result<(), tera::Error> {
let path = path.as_ref().canonicalize()?;
let str = String::from_utf8_lossy(src).to_string();
for (_, [_, layout_path]) in EXPANSION_RE
.captures_iter(&str.as_str())
.map(|c| c.extract())
{
let path = PathBuf::from(path)
let path = path
.canonicalize()?
.parent()
.map(|p| p.join(layout_path))
.unwrap();
self.tera
.add_template_file(&path.canonicalize().unwrap(), Some(layout_path))?;
let next_template = fs::read(&path)?;
let path_str = path.to_string_lossy().to_string();
self.load_template(path_str.as_str(), &next_template)?;
self.load_template(&path, &next_template)?;
self.tera
.add_template_file(&path, Some(layout_path))?;
}
Ok(())
@ -79,7 +84,7 @@ impl<'a> Parse for TeraParser<'a> {
};
if self.options.auto_load_layouts {
self.load_template(path, src).map_err(err)?;
self.load_template(&path, src).map_err(err)?;
}
let template = String::from_utf8_lossy(src).to_string();
@ -98,17 +103,19 @@ impl<'a> Parse for TeraParser<'a> {
#[cfg(test)]
mod tests {
use std::fs;
use roxy_core::roxy::Parse;
use crate::{TeraParser, TeraParserOptions};
#[test]
fn capture_test() {
let mut tera = tera::Tera::default();
let mut parser = TeraParser::new(&mut tera, TeraParserOptions::default());
let data = b"<p>{% include \"test.html\" %}</p>";
let mut dst = Vec::new();
parser.parse("test.html", data, &mut dst);
println!("{dst:?}");
}
//#[test]
//fn capture_test() {
// let mut tera = tera::Tera::default();
// let mut parser = TeraParser::new(&mut tera, TeraParserOptions::default());
// let data = fs::read("./tests/index.md").unwrap();
// let mut dst = Vec::new();
// parser.parse("./tests/index.md", &data, &mut dst);
// println!("{dst:?}");
//}
}

1
tests/base.html Normal file
View file

@ -0,0 +1 @@
:3

2
tests/index.md Normal file
View file

@ -0,0 +1,2 @@
{% extends "middle.html" %}

2
tests/middle.html Normal file
View file

@ -0,0 +1,2 @@
{% extends "base.html" %}