Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add escaping strategy for JSON #1077

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ private static Map<CharSequence, CharSequence> escapeMap(final String[][] table)
EscapingStrategy JS = value ->
value == null ? null : StringEscapeUtils.escapeEcmaScript(value.toString());

/** Escape variable for JSON. */
EscapingStrategy JSON = value ->
value == null ? null : StringEscapeUtils.escapeJson(value.toString());

/** NOOP escaping. */
EscapingStrategy NOOP = value -> value;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.github.jknack.handlebars;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class EscapingStrategyTest {
@Test
public void shouldEscapeVariableForJSON() throws IOException {
Template template = new Handlebars().with(EscapingStrategy.JSON).compileInline("{{this}}");

assertEquals("\\\"", template.apply("\""));
assertEquals("\\\\", template.apply("\\"));
assertEquals("\\/", template.apply("/"));
}
}