#serde-json #javascript #template #literals #templating

serialize-to-javascript

Serialize a serde::Serialize item to a JavaScript literal template using serde_json

3 releases

0.1.2 Aug 4, 2024
0.1.1 Feb 8, 2022
0.1.0 Feb 8, 2022

#246 in Encoding

Download history 33528/week @ 2024-07-18 33288/week @ 2024-07-25 34977/week @ 2024-08-01 37847/week @ 2024-08-08 37090/week @ 2024-08-15 40485/week @ 2024-08-22 45888/week @ 2024-08-29 42339/week @ 2024-09-05 40281/week @ 2024-09-12 34709/week @ 2024-09-19 40824/week @ 2024-09-26 44036/week @ 2024-10-03 43959/week @ 2024-10-10 42269/week @ 2024-10-17 39776/week @ 2024-10-24 43366/week @ 2024-10-31

176,832 downloads per month
Used in 169 crates (7 directly)

MIT/Apache

16KB
107 lines

Serialize to JavaScript

This library provides serialization from serde::Serialize into JavaScript utilizing serde_json. It also provides a very simple templating mechanism along with derive macros to automatically derive them for suitable types.

[dependencies]
serialize-to-javascript = "0.1"

Examples

Serialization

use serialize_to_javascript::{Options, Serialized};

fn main() -> serialize_to_javascript::Result<()> {
    let raw_value = serde_json::value::to_raw_value("foo'bar")?;
    let serialized = Serialized::new(&raw_value, &Options::default());
    assert_eq!(serialized.into_string(), "JSON.parse('\"foo\\'bar\"')");
    Ok(())
}

Templating

main.rs:

use serialize_to_javascript::{default_template, DefaultTemplate, Options, Serialized, Template};

#[derive(Template)]
#[default_template("keygen.js")]
struct Keygen<'a> {
    key: &'a str,
    length: usize,

    #[raw]
    optional_script: &'static str,
}

fn main() -> serialize_to_javascript::Result<()> {
    let keygen = Keygen {
        key: "asdf",
        length: 4,
        optional_script: "console.log('hello, from my optional script')",
    };

    let _output: Serialized = keygen.render_default(&Options::default())?;

    Ok(())
}

keygen.js:

const keygenKey = __TEMPLATE_key__
const keygenLength = __TEMPLATE_length__

__RAW_optional_script__

// app logic, we are ensuring the length is equal to the expected one for some reason
if (keygenKey.length === keygenLength) {
    console.log("okay!")
} else {
    console.error("oh no!")
}

License

Licensed under either of Apache License 2.0, Version or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.7–1.6MB
~34K SLoC