Interpolating strings without including escaped characters

I'm trying to turn a file path into a string that will be included in a liquid template for a test. I need the formatted string to look like {% include '/this/file/path.liquid' %}. I'm getting an error because liquid says "Partial does not exist." I believe this is because the string being passed to the command that uses the liquid template is actually {% include \\\"\\\"/this/file/path.liquid\\\"\" %}. The full code below shows how I'm building the string for my test. If anyone can point out how to build the string correctly I'd appreciate it.

#[cfg(test)]
mod tests {
    use super::*;
    use assert_cmd::prelude::*;
    use predicates::prelude::*;
    use std::fs::File;
    use std::io::{self, Write};
    use std::process::Command;
    use tempfile::tempdir;

    #[test]
    fn passing_template_flag_checks_for_partials() -> Result<()> {
        let temp_dir = tempdir()?;
        let temp_dir_str = temp_dir.path().to_str().unwrap_or("");
        let partial_template_name = "_partial.liquid";
        let partial_template_path = temp_dir.path().join(partial_template_name);
        let mut partial_template_file = std::fs::File::create(&partial_template_path)?;
        writeln!(partial_template_file, "This is the partial content.")?;

        let mut cmd = Command::cargo_bin("leftwm-state").unwrap();
        cmd.arg("-s")
            .arg(format!("{{% include '{:?}' %}}", partial_template_path)) // this is the culprit I think
            .arg("-q");
        println!("{:?}", cmd.output());
        cmd.assert().success();

        drop(partial_template_file);
        temp_dir.close()?;
        Ok(())
    }
}

{:?} prints the Debug representation of something. If you want to just print a string, you use {} which invokes Display instead.

fn main() {
    println!("{}", "I say \"hi\"");     //  I say "hi"
    println!("{:?}", "I say \"hi\"");   //  "I say \"hi\""
}

More on this here: std::fmt - Rust


Notice, of course, that if you simply use {} inside ' as you have here, then an unescaped ' will close the quote and allow arbitrary page content to be written, which may be a security risk depending on the context. You may want to escape the string according to whatever rules are used to escape in liquid.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.