Search code examples
xpathtwigescaping

Escaping simple quote in TWIG


I'm using this TWIG query:

{% if xpath('md_file','//Archive/DOSSIER_MDPH[contains("#FILENAME#", Identifiant)]') %}{{ xpath('md_file','//Archive/DOSSIER_MDPH[contains("#FILENAME#", Identifiant)]/Personne/LIBLDOMA') }} {% endif %}

Sometimes the value of #FILENAME# includes the ' character (simple quote). When this is the case, I get an error indicating that the request is badly formed. For exemple :

1. {% if xpath('md_file','//Archive/DOSSIER[contains("08 - Fiche d'option.pdf", Identifiant)]') %}{{ xpath('md_file','//Archive/DOSSIER[contains("08 - Fiche d'option.pdf", Identifiant)]/Personne/LIBLDOMA') }} {% endif %}^^^ Unexpected "}"

How do you escape the simple quote? I've tried adding an \ before the #FILENAME# but it doesn't work. I've also tried replacing the " with '.


Solution

  • I finally found the solution:

    {% set escapedFilename = "#FILENAME#"|escape %}
    {% if xpath('md_file', '//Archive/DOSSIER[contains("' ~ escapedFilename ~ '", Identifiant)]') %}
    Name: {{ xpath('md_file', '//Archive/DOSSIER[contains("' ~ escapedFilename ~ '", Identifier)]/Personne/LIBLDOMA') }}{% endif %}