{

How to display images in Hugo with examples | Hugo Image shortcode


There are multiple ways we can insert images in Hugo’s posts.

Hugo’s posts are indifferent.

Hugo posts are written in markdown files. These are plain text content with special syntax. Adding an image to markdown files in Hugo

Here is a syntax for adding images to posts in Hugo

![your image](/post/images/your-image.png)
  • Using Figure shortcode

the figure is an inbuilt shortcode provided by Hugo’s static generator

syntax

alt text string

title

  • using custom shortcut if we want full control over how we want to display. We can write a shortcode for image displays.

Here is an shortcode html file image.html in layout/shortcodes folder It contains img tag and set src,alt width attributes

<!-- Get src param from shortcode -->
{{ $src := $.Get "src"}}
{{ $image := .Page.Resources.GetMatch (.Get "src") }}
{{ $file := path.Join (path.Dir .Page.File.Path) $image }}
{{ $stat := os.Stat $file }}

<!-- Get alt param from shortcode -->
{{ $alt := $.Get "alt"}}

{{- /* This shortcode create img tag with lazy loading
Params:
- "src" : relative path of image in directory "static/images/"
*/ -}}
{{- with .Get "src" }}
{{- $src := . }}
{{ with (imageConfig (printf "images/%s" . )) }}

<img class="img-fluid" src="{{ printf " /images/%s" $src | absURL }}" alt="{{ $alt }}" width="{{.Width}}"
  height="{{.Height}}" loading="lazy" decoding="async">
{{ end }}
{{- else }}
{{- errorf "missing value for param 'name': %s" .Position }}
{{- end }}

Here is an example

Primeng Angular Tutorials with examples
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.