HUGO

  • News
  • Docs
  • Themes
  • Showcase
  • Community
  • GitHub
Star

What's on this Page

  • Find Resources in /assets
  • Get Resource with resources.Get and resources.GetRemote
  • Copy a Resource
  • Copy a Resource
  • Asset directory
  • Go Pipes
  • Method aliases
  • Caching
ASSET MANAGEMENT

Hugo Pipes Introduction

Hugo Pipes is Hugo’s asset processing set of functions.

Find Resources in /assets

This is about the global Resources mounted inside /assets. For the .Page scoped Resources, see Page Resources.

Note that you can mount any directory into Hugo’s virtual assets folder using the Mount Configuration.

FunctionDescription
resources.GetGet locates the filename given in Hugo’s assets filesystem and creates a Resource object that can be used for further transformations. See Get Resource with resources.Get and resources.GetRemote.
resources.GetRemoteSame as Get, but it accepts remote URLs. See Get Resource with resources.Get and resources.GetRemote.
resources.GetMatchGetMatch finds the first Resource matching the given pattern, or nil if none found. See Match for a more complete explanation about the rules used.
resources.MatchMatch gets all resources matching the given base path prefix, e.g “.png” will match all png files. The “” does not match path delimiters (/), so if you organize your resources in sub-folders, you need to be explicit about it, e.g.: “images/*.png”. To match any PNG image anywhere in the bundle you can do “**.png”, and to match all PNG images below the images folder, use “images/**.jpg”. The matching is case insensitive. Match matches by using the files name with path relative to the file system root with Unix style slashes (/) and no leading slash, e.g. “images/logo.png”. See https://github.com/gobwas/glob for the full rules set.

See the GoDoc Page for the resources package for an up to date overview of all template functions in this namespace.

Get Resource with resources.Get and resources.GetRemote

In order to process an asset with Hugo Pipes, it must be retrieved as a Resource using resources.Get or resources.GetRemote.

With resources.Get, the first argument is a local path relative to the assets directory/directories:

{{ $local := resources.Get "sass/main.scss" }}

With resources.GetRemote, the first argument is a remote URL:

{{ $remote := resources.GetRemote "https://www.example.com/styles.scss" }}

resources.Get and resources.GetRemote return nil if the resource is not found.

You can get information about the HTTP Response using .Data in the returned Resource. This is especially useful for HEAD request without any body. The Data object contains:

StatusCode
The HTTP status code, e.g. 200 Status
The HTTP status text, e.g. “200 OK” TransferEncoding
The transfer encoding, e.g. “chunked” ContentLength
The content length, e.g. 1234 ContentType
The content type, e.g. “text/html”

Copy a Resource

resources.Copy allows you to copy almost any Hugo Resource (the one exception is the Page), possibly most useful for renaming things:

{{ $resized := $image.Resize "400x400" |  resources.Copy "images/mynewname.jpg" }}
<img src="{{ $resized.RelPermalink }}">

Caching

By default, Hugo calculates a cache key based on the URL and the options (e.g. headers) given.

You can override this by setting a key in the options map. This can be used to get more fine grained control over how often a remote resource is fetched, e.g.:

{{ $cacheKey := print $url (now.Format "2006-01-02") }}
{{ $resource := resource.GetRemote $url (dict "key" $cacheKey) }}

Error Handling

The return value from resources.GetRemote includes an .Err method that will return an error if the call failed. If you want to just log any error as a WARNING you can use a construct similar to the one below.

{{ with resources.GetRemote "https://gohugo.io/images/gohugoio-card-1.png" }}
  {{ with .Err }}
    {{ warnf "%s" . }}
  {{ else }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
  {{ end }}
{{ end }}

Note that if you do not handle .Err yourself, Hugo will fail the build the first time you start using the Resource object.

Remote Options

When fetching a remote Resource, resources.GetRemote takes an optional options map as the second argument, e.g.:

{{ $resource := resources.GetRemote "https://example.org/api" (dict "headers" (dict "Authorization" "Bearer abcd"))  }}

If you need multiple values for the same header key, use a slice:

{{ $resource := resources.GetRemote "https://example.org/api"  (dict "headers" (dict "X-List" (slice "a" "b" "c")))  }}

You can also change the request method and set the request body:

{{ $postResponse := resources.GetRemote "https://example.org/api"  (dict 
    "method" "post"
    "body" `{"complete": true}` 
    "headers" (dict 
        "Content-Type" "application/json"
    )
)}}

Caching of Remote Resources

Remote resources fetched with resources.GetRemote will be cached on disk. See Configure File Caches for details.

Copy a Resource

resources.Copy allows you to copy almost any Hugo Resource (the one exception is the Page), possibly most useful for renaming things:

{{ $resized := $image.Resize "400x400" |  resources.Copy "images/mynewname.jpg" }}
<img src="{{ $resized.RelPermalink }}">

Asset directory

Asset files must be stored in the asset directory. This is /assets by default, but can be configured via the configuration file’s assetDir key.

Asset Publishing

Hugo publishes assets to the publishDir (typically public) when you invoke .Permalink, .RelPermalink, or .Publish. You can use .Content to inline the asset.

Go Pipes

For improved readability, the Hugo Pipes examples of this documentation will be written using Go Pipes:

{{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $style.Permalink }}">

Method aliases

Each Hugo Pipes resources transformation method uses a camelCased alias (toCSS for resources.ToCSS). Non-transformation methods deprived of such aliases are resources.Get, resources.FromString, resources.ExecuteAsTemplate and resources.Concat.

The example above can therefore also be written as follows:

{{ $style := resources.Get "sass/main.scss" | toCSS | minify | fingerprint }}
<link rel="stylesheet" href="{{ $style.Permalink }}">

Caching

Hugo Pipes invocations are cached based on the entire pipe chain.

An example of a pipe chain is:

{{ $mainJs := resources.Get "js/main.js" | js.Build "main.js" | minify | fingerprint }}

The pipe chain is only invoked the first time it is encountered in a site build, and results are otherwise loaded from cache. As such, Hugo Pipes can be used in templates which are executed thousands or millions of times without negatively impacting the build performance.

  • About Hugo
    • Overview
    • Hugo's Security Model
    • Hugo and GDPR
    • What is Hugo
    • Hugo Features
    • The Benefits of Static
    • License
  • Installation
    • Installation overview
    • macOS
    • Linux
    • Windows
    • BSD
  • Getting Started
    • Get Started Overview
    • Quick Start
    • Basic usage
    • Directory Structure
    • Configuration
    • External Learning Resources
  • Hugo Modules
    • Hugo Modules Overview
    • Configure Modules
    • Use Hugo Modules
    • Theme Components
  • Content Management
    • Content Management Overview
    • Organization
    • Page Bundles
    • Content Formats
    • Diagrams
    • Front Matter
    • Build Options
    • Page Resources
    • Image Processing
    • Shortcodes
    • Related Content
    • Sections
    • Content Types
    • Archetypes
    • Taxonomies
    • Summaries
    • Links and Cross References
    • URL Management
    • Menus
    • Static Files
    • Table of Contents
    • Comments
    • Multilingual
    • Syntax Highlighting
  • Templates
    • Templates Overview
    • Templating
    • Template Lookup Order
    • Custom Output Formats
    • Base Templates and Blocks
    • Render Hooks
    • List Templates
    • Homepage Template
    • Section Templates
    • Taxonomy Templates
    • Single Page Templates
    • Content View Templates
    • Data Templates
    • Partial Templates
    • Shortcode Templates
    • Local File Templates
    • 404 Page
    • Menu Templates
    • Pagination
    • RSS Templates
    • Sitemap Templates
    • Robots.txt
    • Internal Templates
    • Template Debugging
  • Functions
    • Functions Quick Reference
    • .AddDate
    • .Format
    • .Get
    • .GetPage
    • .HasMenuCurrent
    • .IsMenuCurrent
    • .Param
    • .Render
    • .RenderString
    • .Scratch
    • .Store
    • .Unix
    • absLangURL
    • absURL
    • after
    • anchorize
    • append
    • apply
    • base64
    • chomp
    • complement
    • cond
    • countrunes
    • countwords
    • crypto.FNV32a
    • default
    • delimit
    • dict
    • duration
    • echoParam
    • emojify
    • eq
    • errorf and warnf
    • fileExists
    • findRE
    • first
    • float
    • ge
    • getenv
    • group
    • gt
    • hasPrefix
    • highlight
    • hmac
    • htmlEscape
    • htmlUnescape
    • hugo
    • humanize
    • i18n
    • Image Filters
    • in
    • index
    • int
    • intersect
    • isset
    • jsonify
    • lang
    • lang.Merge
    • last
    • le
    • len
    • lower
    • lt
    • markdownify
    • Math
    • md5
    • merge
    • ne
    • now
    • os.Stat
    • partialCached
    • path.Base
    • path.BaseName
    • path.Clean
    • path.Dir
    • path.Ext
    • path.Join
    • path.Split
    • plainify
    • pluralize
    • print
    • printf
    • println
    • querify
    • range
    • readDir
    • readFile
    • ref
    • reflect.IsMap
    • reflect.IsSlice
    • relLangURL
    • relref
    • relURL
    • replace
    • replaceRE
    • safeCSS
    • safeHTML
    • safeHTMLAttr
    • safeJS
    • safeURL
    • seq
    • sha
    • shuffle
    • singularize
    • site
    • slice
    • slicestr
    • sort
    • split
    • string
    • strings.Contains
    • strings.ContainsAny
    • strings.Count
    • strings.FirstUpper
    • strings.HasSuffix
    • strings.Repeat
    • strings.RuneCount
    • strings.TrimLeft
    • strings.TrimPrefix
    • strings.TrimRight
    • strings.TrimSuffix
    • substr
    • symdiff
    • templates.Exists
    • time
    • time.Format
    • time.ParseDuration
    • title
    • transform.Unmarshal
    • trim
    • truncate
    • union
    • uniq
    • upper
    • urlize
    • urlquery
    • urls.Parse
    • where
    • with
  • Variables
    • Variables Overview
    • Site Variables
    • Page Variables
    • Shortcode Variables
    • Pages Methods
    • Taxonomy Variables
    • File Variables
    • Menu Variables
    • Git Variables
    • Sitemap Variables
  • Hugo Pipes
    • Hugo Pipes Overview
    • Hugo Pipes
    • Sass / SCSS
    • PostProcess
    • PostCSS
    • JavaScript Building
    • Babel
    • Asset minification
    • Asset bundling
    • Fingerprinting and SRI
    • Resource from Template
    • Resource from String
  • CLI
  • Troubleshooting
    • Troubleshoot
    • FAQ
    • Build Performance
  • Tools
    • Developer Tools Overview
    • Migrations
    • Starter Kits
    • Frontends
    • Editor Plug-ins
    • Search
    • Other Projects
  • Hosting & Deployment
    • Hosting & Deployment Overview
    • Hugo Deploy
    • Host on 21YunBox
    • Host on AWS Amplify
    • Host on Azure Static Web Apps
    • Host on Netlify
    • Host on Render
    • Host on Firebase
    • Host on GitHub
    • Host on GitLab
    • Host on KeyCDN
    • Host on Cloudflare Pages
    • Deployment with Rsync
    • Deployment with Rclone
    • Hosting on Azure Static Web Apps
  • Contribute
    • Contribute to Hugo
    • Development
    • Documentation
    • Themes
  • Maintenance
Last updated: March 16, 2023: resources.GetRemote: minor improvement (#2002) (bcbc519b)
Improve this page
By the Hugo Authors
Hugo Logo
  • File an Issue
  • Get Help
  • Discuss Source Code
  • @GoHugoIO
  • @spf13
  • @bepsays

Netlify badge

 

Hugo Sponsors

 

The Hugo logos are copyright © Steve Francia 2013–2023.

The Hugo Gopher is based on an original work by Renée French.

  • News
  • Docs
  • Themes
  • Showcase
  • Community
  • GitHub
  • About Hugo
  • Installation
  • Getting Started
  • Hugo Modules
  • Content Management
  • Templates
  • Functions
  • Variables
  • Hugo Pipes
  • CLI
  • Troubleshooting
  • Tools
  • Hosting & Deployment
  • Contribute
  • Maintenance