0

I'm trying to figure out why pythons' format

OUTPUT_HTML_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    'formats',
    'html')
with open(os.path.join(OUTPUT_HTML_PATH, 'index.html'), 'r') as f:
    OUTPUT_HTML_PAGE = f.read()

OUTPUT_HTML_PAGE.format(feedback_json=json.dumps(
            feedback, indent=2, sort_keys=True),
            resources_path=args.resources_path)

The format succeeded in case of the old index.html.

Once I've tried to change the index.html with adding a script tag like so:

<script type="application/javascript">
    function loadScript(url, callback){
        a=1
    }
</script>

I'm getting

KeyError: '\n            a=1\n        '

My function was simplified to reduce complexity

WebQube
  • 8,510
  • 12
  • 51
  • 93

2 Answers2

2

For python you are using this string:

"""<script type="application/javascript">
    function loadScript(url, callback){
        a=1
    }
  </script>"""

If you check the format documentation, you will see that it uses '{}' as the place holder where the input data will be placed. So in your string you have a=1 inside that place holder hence python doesn't know what to do with it.

In order to solve this, you woul have to add double "{{}}" to scape them in the string so python doesn't recognize them as a formatting token:

"""<script type="application/javascript">
    function loadScript(url, callback){{
        a=1
    }}
  </script>"""
Netwave
  • 40,134
  • 6
  • 50
  • 93
0

You need to escape any { or } characters that are not part of a formatting slot; do so by doubling them:

<script type="application/javascript">
    function loadScript(url, callback){{
        a=1
    }}
  </script>

You may want to look at specialised templating libraries however, such as Jinja2 or Mako, or any of the other widely used engines; these let you use conditionals and other programming constructs too, not just simply interpolate values into fixed slots.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343