Skip to content

Mustache.escape should include the key | Use case: instead of not rendering empty variables, ignore them and get the {{key}}. #843

@kelvinauta

Description

@kelvinauta

When a variable in a view is empty, Mustache.render simply doesn't render anything. I'd like that when a variable is empty, it just gets ignored and the original text {{key}} is rendered instead. Here's an example with the normal output and the output I want:

Mustache.render("{{foo}} and {{bar}}", {foo: "foo"})

// Normal Output:
// foo and
// Desired Output:
// foo and {{bar}}

I thought the solution would be Mustache.escape, but the properties passed to the function are just strings with values that only get executed if the value is not empty. So, I can't do anything with empty variables.

// Current solution:
Mustache.escape = (value) => value; // This function only executes when the value exists

// What I'd like to do:
Mustache.escape = (value, key, tags) => value || `${tags[0]}${key}${tags[1]}`; // Executes whether the value is empty or not

Maybe I've missed something. If anyone knows how to achieve this, I would really appreciate the help. For now, my workaround looks something like this, but I don't like it at all:

Mustache.render("{{foo}}", {foo: "{{foo}}"}) // Preprocess the object so that empty variables are replaced with a string, allowing Mustache to render them

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions