Embed an iframe in Hugo content
Posted: Sunday 14th April 2024 Read Time: 3 minutesQuick and dirty method
Hugo’s rendering engine is smart. If you need a quick solution, you can add almost any HTML to your content, and it will render as you expect:
|
|
This will render the iframe
in place with the default dimensions and might be
all you need.
For reference, the default sizing of an iframe
is 300 pixels wide by 150
pixels tall.
But we can do better.
The better method
We can utilize shortcodes to accomplish the same thing in a more structured way.
Let’s make a new shortcode file:
|
|
Bear in mind the name of the file inside the shortcodes
directory dictates
the name of the shortcode.
Now we can use this shortcode in any of our markdown content:
|
|
This will render an iframe
100 pixels wide by 50 pixels tall.
Using shortcodes to accomplish this, we have a tidy, consistent and
repeatable method of embedding iframe
s into our content.
Content Security Policy
Depending on your
Content Security Policy,
you might find that the iframe
refuses to load. The header X-Frame-Options
controls this. By setting the value to SAMEORIGIN
, it will, as the name suggests,
allow you to load iframe
s from the same origin.
If you want to load a resource from an external origin, you will need to
modify your Content-Security-Policy
header, specifically the frame-ancestors
policy. You can read more about that header
here.