davidchall / jinjar

Templating engine for R inspired by Jinja
https://davidchall.github.io/jinjar
Other
44 stars 1 forks source link

Problem parsing double quote #28

Closed PhoebeJacinda closed 1 year ago

PhoebeJacinda commented 1 year ago

I would like to check if a value is equal to this string -> "/ " and the quotation mark is a part of the value. I tried to run {% if x != '"/ "' %} but the rendering did not work. Is there any way to work around it so I can completely render the quotation mark?

davidchall commented 1 year ago

Hi @PhoebeJacinda - yes, this is achievable in jinjar. Your goal is to compare a variable to a string literal within your template. You've encountered difficulty around escaping your string literal.

  1. Every string literal must be surrounded by double quotation marks. E.g., x == "yes" compares variable x to the string yes.
  2. Your string literal includes double quotation marks, so we must escape them using a backslash. E.g., x == "\"yes\"" compares variable x to the string "yes".
  3. Finally, if your template is defined within an R source file (as below), then these backslashes also need to be escaped using a further backslash. E.g., x == "\\"yes\\"" compares variable x to the string "yes". If you are rendering a template defined in a text file, then this additional escaping is not required.

In summary, here's some example code showing how to make your desired string comparison.

library(jinjar)

template <- '{% if x == "\\"/ *\\"" -%}Hello world{% endif %}'

render(template, x = "nope")
#> [1] ""
render(template, x = '"/ *"')
#> [1] "Hello world"

Created on 2023-02-06 with reprex v2.0.2

davidchall commented 1 year ago

Leaving ticket open to remind me to add this question to the docs.