Image Processing Outside Bundles

百般思念 提交于 2019-12-21 17:06:58

问题


Is it possible to use Hugo 0.32's new image processing feature for images in other folders?

For example, I have a site that is already structured in a format with all media in a separate /content/images folder, instead of beside each entry as a page bundle.


回答1:


It is possible to access resources of a page from it's reference, so this is possible with a pretty simple setup.

Create an _index.md file in the content/images folder with simple front-matter similar to below.

content/images/_index.md

---
title: Media Folder
---

This will allow you to access the resources for images within the section from the site context and get the page. If you don't want this to show up as an actual page on your published website, you can add headless: true.

Listing the images from another Page Template

{{ with .Site.GetPage "section" "images" }}
  <h2>{{ .Title }}</h2>
  {{ $resources := .Resources.ByType "image"}}
  {{ range $resources }}
    {{ with . }}
      <img style="max-width: 100%;" src="{{ .RelPermalink }}">
      <br />
    {{ end }}
  {{ end }}
{{ end }}

Listing and resizing the resource images

{{ with .Site.GetPage "section" "images" }}
  <h2>From {{ .Title }} (images)</h2>
  {{ $resources := .Resources.ByType "image"}}
  {{ range $resources }}
    {{ with . }}
      {{ $image200x := (.Resize "200x") }}
      {{ $image400x := (.Resize "400x") }}
      <img src="{{ $image200x.RelPermalink }}">
      <img src="{{ $image400x.RelPermalink }}">
      <br />
    {{ end }}
  {{ end }}
{{ end }}

These were examples to show how to access the resources from within the images location from another location in the bundle. You can also access the individual image by name by using .Resources.GetByPrefix "logo" to get the image resource directly.

Access an Image resource by name

In the front matter of the page you would include a field imagename: logo as an example, then:

{{ $page := . }}
{{ with .Site.GetPage "section" "images" }}
  {{ with .Resources.GetByPrefix $page.Params.imagename }}
    {{ $image200x := (.Resize "200x") }}
    {{ $image400x := (.Resize "400x") }}
    <img src="{{ $image200x.RelPermalink }}">
    <img src="{{ $image400x.RelPermalink }}">
    <br />
  {{ end }}
{{ end }}

NOTE: You could also access these images from the markdown, but that will require a shortcode setup like in the Hugo docs and I have included examples of a shortcode in the GitHub example link below.

Here is the GitHub repository of the example



来源:https://stackoverflow.com/questions/48213883/image-processing-outside-bundles

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