mitsuhiko / minijinja

MiniJinja is a powerful but minimal dependency template engine for Rust compatible with Jinja/Jinja2
https://docs.rs/minijinja/
Apache License 2.0
1.63k stars 95 forks source link

May I ask how to convert my JSON string into a JSON variable in the template #533

Closed sunkaifei closed 3 months ago

sunkaifei commented 3 months ago

The fields stored in my database are JSON strings, and I want to convert this field directly into a variable on the template page, and then output each content in JSON through this variable, or is there any other way to directly output it?

sunkaifei commented 3 months ago

The current solution is

// 自定义过滤器函数
pub fn to_json_filter(value: &Value) -> Result<Value, Error> {
    // 处理输入的 value,假设输入是一个字符串
    let json_str = value.as_str().unwrap_or("");
    match serde_json::from_str::<Value>(json_str) {
        Ok(json_value) => {
            Ok(json_value)
        },
        Err(err) => { 
            log::error!("Error parsing JSON: {}", err);
            Ok(Value::from_safe_string("Json标签解析失败".to_string()))   
        },
    }
}
mitsuhiko commented 3 months ago

A custom JSON parsing filter is most likely the right solution. Another option would be to parse the data before it's passed to the template.