Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Processing Outside Bundles

Tags:

hugo

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.

like image 632
tech4him Avatar asked Jan 11 '18 18:01

tech4him


1 Answers

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

like image 153
talves Avatar answered Oct 19 '22 00:10

talves