home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

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:

July 2023
Code
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")
    ))
}
Code
    <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 page context variable

  • The data is placed in a hidden input element to start with then scrubbed and output in the pre tag when the page is loaded

  • I have optional values that come across in the origial data as None without quotes. The script adds the qutoes to diminish parsing issues

═══ § ═══

Footnotes And References