From 8a044c3eca99f8b3ae5d894a558581f30c7da4dd Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Sat, 27 Jul 2024 20:26:26 +0800 Subject: [PATCH] lib/data: add function for rendering Mustache templates --- lib/data.nix | 20 ++++++++++++++++++++ tests/lib/data/default.nix | 9 +++++++++ tests/lib/data/templates/sample.mustache | 1 + 3 files changed, 30 insertions(+) create mode 100644 tests/lib/data/templates/sample.mustache diff --git a/lib/data.nix b/lib/data.nix index 74688f28..8bffae7f 100644 --- a/lib/data.nix +++ b/lib/data.nix @@ -44,4 +44,24 @@ } '' tera --out "$out" ${extraArgs'} --template "${template}" "${contextFile}" ''; + + /* Render a Mustache template given a parameter set powered by `mustache-go`. + Also typically used as an IFD. + + Type: renderMustacheTemplate :: Attrs -> Path + + Example: + renderMustacheTemplate { path = ./template.mustache; context = { hello = 34; }; } + => /nix/store/HASH-mustache-render-template + */ + renderMustacheTemplate = { template, context, extraArgs ? { } }: + let + extraArgs' = lib.cli.toGNUCommandLineShell { } extraArgs; + in pkgs.runCommand "mustache-render-template" { + nativeBuildInputs = with pkgs; [ mustache-go ]; + context = builtins.toJSON context; + passAsFile = [ "template" "context" ]; + } '' + mustache "$contextPath" "${template}" ${extraArgs'} > $out + ''; } diff --git a/tests/lib/data/default.nix b/tests/lib/data/default.nix index d647a9a4..05ce7a48 100644 --- a/tests/lib/data/default.nix +++ b/tests/lib/data/default.nix @@ -30,4 +30,13 @@ lib.runTests { }); expected = builtins.readFile ./fixtures/sample.tera; }; + + testRenderMustacheTemplate = { + expr = builtins.readFile (self.data.renderTeraTemplate { + template = ./templates/sample.mustache; + context = lib.importJSON ./data/sample.json; + }); + # There the same lol. + expected = builtins.readFile ./fixtures/sample.tera; + }; } diff --git a/tests/lib/data/templates/sample.mustache b/tests/lib/data/templates/sample.mustache new file mode 100644 index 00000000..8fe25f99 --- /dev/null +++ b/tests/lib/data/templates/sample.mustache @@ -0,0 +1 @@ +{{ hello }}