Resize image in Hugo (v 0.32.x) in markdown

雨燕双飞 提交于 2019-12-06 04:39:48

Using my newer version of Hugo (v0.53) I had to adapt the answer by JoostS a bit:

  1. Created a page bundle
  2. Modified the shortcode to look like this at the start:

    
    {{ $original := .Page.Resources.GetMatch (print "images/" (.Get 0) "*") }}
    

I don't think you can use it like this (in markdown). In markdown you will have to use a shortcode, as the image has to be accessible in the Go templating language before you can attach the resize command.

You will need to make sure you have included your images within the content of your page usually at the level of the page itself unless you reference them using the answer I link in the note below.

NOTE: You can access resources from an outside section as in this answer

Write a shortcode

layouts/shortcodes/imgresize.html

{{ $original := .Page.Resources.GetByPrefix (.Get 0) }}
{{ $options := .Get 1 }}
{{ .Scratch.Set "image" ($original.Resize $options) }}
{{ $image := .Scratch.Get "image" }}
<img src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}">

[Alternative] Shortcode accessing resource under content/media section

{{ $imagename := (.Get 0) }}
{{ $options := .Get 1 }}
{{ with .Site.GetPage "section" "media" }}
  {{ $original := .Resources.GetByPrefix  $imagename }}
  {{ with ($original.Resize $options) }}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
  {{ end }} 
{{ end }}

Call the shortcode from within the markdown of the page.

{{< imgresize pdf "50x50" >}}

pdf refers to the image by its name prefix to get the resource.

Using a sub folder page to access the resources

In the next example shortcode you must have a page at the same level as your images. Include an index.md at the same level (example: content/media/logos/index.md)

add layouts/shortcodes/logo-resize.html

{{ $imagename := (.Get 0) }}
{{ $options := .Get 1 }}
{{ with .Site.GetPage "page" "media/logos/index.md" }}
  {{ $original := .Resources.GetByPrefix  $imagename }}
  {{ with ($original.Resize $options) }}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
  {{ end }} 
{{ end }}

Call the shortcode

{{< logo-resize pdf "50x50" >}}

GitHub Example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!