Using JSON in data attributes with JS |
11-14-2017, 05:34 PM
(This post was last modified: 11-14-2017, 05:36 PM by ivantcholakov. Edit Reason: typos )
For views I use the Twig parser and here is a test on how I would do this:
Code: <div id="test_element" data-json="{{ '{ "value_1": "A test string value.", "value_2": 2 }'|e('html_attr') }}"></div> This works, and the produced HTML code looks like this: Code: <div id="test_element" data-json="{ "value_1": "A test string value.", "value_2": 2 }"></div> For PHP views this example would be: Code: <div id="test_element" data-json="<?php echo html_attr_escape('{ "value_1": "A test string value.", "value_2": 2 }'); ?>"></div> The helper function html_attr_escape() is introduced by me, it calls the Twig's escaper to do the job. https://github.com/ivantcholakov/starter...n.php#L283 If you don't need Twig to be installed in your project, you can implement html_attr_escape() by using the escaper form Zend. https://github.com/zendframework/zend-es...r.php#L155 The escapers of Twig seem to be ported from Zend. I can see that CodeIgniter 4 would use the Zend Escaper, you can back-port this function: https://github.com/bcit-ci/CodeIgniter4/...n.php#L219 : Code: <div id="test_element" data-json="<?php echo esc('{ "value_1": "A test string value.", "value_2": 2 }', 'attr'); ?>"></div> In conclusion, you should find a way to escape the data html attribute as html attribute, it does not matter whether it would contain json data or something else. I think, the trivial way would be the best here, everyone would understand it without getting bored or tired. |
Messages In This Thread |
Using JSON in data attributes with JS - by skunkbad - 11-14-2017, 02:16 PM
RE: Using JSON in data attributes with JS - by ivantcholakov - 11-14-2017, 05:34 PM
RE: Using JSON in data attributes with JS - by skunkbad - 11-14-2017, 10:24 PM
RE: Using JSON in data attributes with JS - by ivantcholakov - 11-14-2017, 10:48 PM
RE: Using JSON in data attributes with JS - by skunkbad - 11-15-2017, 12:43 AM
RE: Using JSON in data attributes with JS - by ivantcholakov - 11-15-2017, 07:33 AM
RE: Using JSON in data attributes with JS - by skunkbad - 11-15-2017, 09:22 AM
|