画像処理ショートコード

parials/func/GetHtmlImgTag.html

  • 関数的に呼び出す(置き場所やファイル名は任意)
  • partial "xxx.html" arg では引数を1個しかとれない(?)ため、dict 形式で渡す
  • if isset でキーが存在するかを確認する
{{ $destination := .Image }}

{{ $text := "" }}
{{ if isset . "Text" }}{{ $text = .Text }}
{{ else }}{{ $text = .Page.Title }}
{{ end }}

{{ $width := ""}}
{{ $height := ""}}
{{ if isset . "Width" }}{{ $width = .Width }}{{ end }}
{{ if isset . "Height" }}{{ $height = .Height }}{{ end }}

{{- if strings.HasPrefix $destination "http" -}}
  <img loading="lazy" src="{{ $destination | safeURL }}" alt="{{ $text }}" title="{{ $text }}" />
{{- else -}}
  {{ if and (not $width) (not $height)}}
    {{/*  Measure the image size if no size is given as an argument  */}}
    {{ with imageConfig ( printf "static/%s" $destination ) }}{{ $width = .Width }}{{ $height = .Height }}{{ end }}
  {{ end }}
  <img loading="lazy" src="{{ $destination | safeURL }}" alt="{{ $text }}" title="{{ $text }}" width={{ $width }} height="{{ $height }}"/>
{{- end -}}

呼び出し方

{{ partial "func/GetHtmlImgTag.html" (dict "Page" . "Image" $featured_image "Width" 350 "Height" 220 ) }}

Partial で任意の数の引数を与えたい場合

{{ partial "my-partial.html" (dict "context" . "args1" "argas-value-1)" "args2" 2 }}