Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Pretty Print Raw MiniJinja JSON Data On A Template

I use MiniJinja mj to create the templates for my site. The output data comes in from Serde se in a JSON like syntax. I use this snippet to pretty print it so it's easier to work with :

[] this is new code to look at :

rust
pub fn show(&self, args: &[Value]) -> Option<String> {
    let content = serde_json::to_string_pretty(
        &serde_json::from_str::<serde_json::Value>(&args[0].to_string()).unwrap(),
    );
    let code_type = "json";
    let syntax_set = SyntaxSet::load_defaults_newlines();
    let syntax = syntax_set.find_syntax_by_token(code_type).unwrap();
    let mut html_generator =
        ClassedHTMLGenerator::new_with_class_style(syntax, &syntax_set, ClassStyle::Spaced);
    for line in LinesWithEndings::from(&content.unwrap()) {
        let _ = html_generator.parse_html_for_line_which_includes_newline(line);
    }
    let initial_html = html_generator.finalize();
    let output_html: Vec<_> = initial_html
        .lines()
        .map(|line| format!(r#"<span class="linenumber">{}</span>"#, line))
        .collect();

    Some(format!(
        "<pre><code>{}</code></pre>",
        output_html.join("\n")
    ))
}
javascript
    <input type="hidden" id="neo_string" value="{% autoescape true %}{{ page.all_sections() }}{% endautoescape %}" />
    <pre id="neo_formatted"></pre>
    <script>
      const updateIt = () => {
        neo_formatted.innerText = JSON.stringify(
          JSON.parse(neo_string.value.replaceAll('None', `"None"`)),
          null,
          2
        )
      }
      document.addEventListener('DOMContentLoaded', updateIt)
    </script>

- This goes in a template that receives data in a [TODO: Code shorthand span ] context variable

- The data is placed in a hidden input element to start with then scrubbed and output in the [TODO: Code shorthand span ] tag when the page is loaded

- I have optional values that come across in the origial data as [TODO: Code shorthand span ] without quotes. The script adds the qutoes to diminish parsing issues

Footnotes And References