Trying to understand trim + absURL?

I see the Ananke theme uses trim + absURL to solve relative image issues (code below). My understanding is trim + absURL works for root-level assets only. Is that right? Can you use trim + absURL for sub-directory assets (ex: images in an “img” folder at the the root level) instead of having to manually add “img/” to each content pieces’ featured_image in the front matter?

{{ if .Params.featured_image }}
      {{/* Trimming the slash and adding absURL make sure the image works no matter where our site lives */}}
      {{ $featured_image := (trim $featured_image "/") | absURL }}
        <div class="fl-l w-50-l {{ if .Params.featured_image }} w-60-ns pl3-ns{{ end }} tl tc-ns pt3 pt4-m pt6-l">
          <a class="f6 f5-ns fw6 dib ph3 ph4-ns pv2 pv3-ns grow no-underline" href="{{ .URL }}">
            <img src="{{ $featured_image }}" class="db" alt="image from {{ .Title }}">
    {{ end }}

You could add the directory directly to your code, if you like. Trim may or may not be necessary, it’s just there to handle a wide variety of potential scenarios. Make sense?

Relative links cause me no end of grief @budparr so I’m certainly keen to follow your path and make link life easier for me. For curiosity sake, is there a function that opposes “trim”? What would you use, for example, to add an “img” directory into {{ $featured_image := (trim $featured_image “/”) | absURL }}?

I’m not sure you need trim at all since your goal is to make sure the templating works regardless of where the site “lives.” You can concatenation the value as well before running it through the URL funcs…

The easiest thing is to just do what @rdwatters said. I very often use replace to swap out my local directory for a CDN directory (I use imgix for image manipulation). It looks like this:

{{ $background_image := .Params.featured_image | replace "(/uploads)" .Site.Params.image_url }}

1 Like

@budparr 's solution is great.

I am by no means saying this is better or “correct” since I’m still a bit lost on what your intentions are w/r/t being able to put the site anywhere, but here’s a quick snippet that gives you an idea of how you can use add to concatenate strings if you’re not comfortable with printf:

{{ with .Params.featured_image }}
  {{$fi := add ($.Site.Params.imagedir | default "img/") . }}
  <img src="{{$fi | relURL}}" alt="{{$.Params.image_alt | default "Some default description if you want it or maybe try to point to a default site param?"}}">
{{ end }}

Or absURL instead of relURL depending on what your baseURL is in your config…and your preference. Note the use of $ since with rebinds context.

Then you can set the following in config.toml:

	imagedir = "images/"

And if you don’t set it in your config, the templating will fall back to img/ in the above example. HTH.