Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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:

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>

References