──────────────────────────────────────

49. Prepare Reports to Share · Put Report Text into HTML

Generate a heading and paragraph that display the original text as written.

Lesson files · lessons/share-reports/render-report-text

Before you start
- Read input lines and insert their values into an f-string.
- Recognise opening tags and attributes in HTML.

By the end
- Escape a supplied title and note before placing them in heading and paragraph tags.
- Explain how a browser displays angle brackets from the escaped note.

Where you can use it
Put notes from a sign-up form into a browser report while keeping names containing & or angle brackets readable.

An HTML report can open in an ordinary browser. The program supplies the tags, and the input supplies the words inside those tags. Some characters have special meaning in HTML. For example, a browser may treat <meeting> as a tag. Use html.escape() on each piece of input text before placing it between tags. The resulting &lt; and &gt; display as angle brackets when the report opens.

Predict
What words will the browser show for the example paragraph?
- Tea & toast
- Tea &amp; toast

Worked example (example.py)

from html import escape

caption = "Tea & toast"
print(f"<p>{escape(caption)}</p>")


Example result
<p>Tea &amp; toast</p>

Read a title and then a note. Print the escaped title inside h1 tags on the first line and the escaped note inside p tags on the second. Keep the tags in the program and apply escape() to the words from input.

Starter program (starter.py)

title = input()
note = input()
print(f"<h1>{title}</h1>")
print(f"<p>{note}</p>")


Starter input
Robotics & Design
Distance < 3 m

Hint
In each f-string, call escape() inside the braces that hold the input text.

Case 1. Try the sample
Input
Robotics & Design
Distance < 3 m
Expected output
<h1>Robotics &amp; Design</h1>
<p>Distance &lt; 3 m</p>

Case 2. Ordinary words
Input
Garden Club
Planted beans.
Expected output
<h1>Garden Club</h1>
<p>Planted beans.</p>

Case 3. Text that looks like a tag
Input
Café
Meet at <stage>
Expected output
<h1>Café</h1>
<p>Meet at &lt;stage&gt;</p>

Stretch
Copy the finished output into a UTF-8 text file named note.html and open it in your browser. Compare what you see with the printed HTML.

Reflect
Why should you escape the title and note before adding the report tags?

Check your prediction
Tea & toast The browser displays the character reference &amp; as an ampersand.
