Skip to content

Instantly share code, notes, and snippets.

@eschmar
Created October 28, 2018 10:20
Show Gist options
  • Save eschmar/26e472154377ec4ded3b1bc77a0f8c3b to your computer and use it in GitHub Desktop.
Save eschmar/26e472154377ec4ded3b1bc77a0f8c3b to your computer and use it in GitHub Desktop.
Inject the data encoded in JSON
{#
https://twitter.com/dunglas/status/1054993007332724738?s=03
Inject the data encoded in JSON in a `<script type="application/json">` tag.
Then access to this element in JS and call `JSON.parse`.
It's secure, elegant and works even with the strictest CSPs.
https://github.com/api-platform/core/blob/master/src/Bridge/Symfony/Bundle/Resources/views/SwaggerUi/index.html.twig#L11-L12
https://github.com/api-platform/core/blob/master/src/Bridge/Symfony/Bundle/Resources/public/init-swagger-ui.js#L6
#}
{# json_encode(65) is for JSON_UNESCAPED_SLASHES|JSON_HEX_TAG to avoid JS XSS #}
<script id="swagger-data" type="application/json">{{ swagger_data|json_encode(65)|raw }}</script>
<script>
const data = JSON.parse(document.getElementById('swagger-data').innerText);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment