Keep images & content together


#82

You can always do something like this:

{{ .Content | replaceRE "<p><img" "<figure><img" | replaceRE "></p>" "></figure>" | safeHTML }}

You can adapt it to add whatever classes or HTML you need.

People complain about Blackfriday wrapping everything in <p> tags but this quirk is particularly useful in cases like this.

Also you can do the above for a specific post type if you don’t need it site-wide.

:wink:


#83

So maybe I’m daft, but how does one go about doing what you say? I’d like to have images along side a blog post, and have those image show up on my homepage which lists the most recent 5 or so posts.


Images in content folder? Simple, but I can't make it work
#84

Just download my custom figure shortcode that I linked earlier and save it to your site’s shortcodes directory in layouts. And then use the figure shortcode as usual.

Then, even if the summaries showing up on the home page have the images from page bundles, they will show up fine.


How to make Hugo work with images any better?
#86

I have been battling with this issue today and came up with a “decent enough” solution for myself that supports the standard markdown image reference but will append the relative location of page level images where needed. This supports using standard markdown for both page bundle level images as well as images in the static directory.

TL;DR - The code finds all images by the src indicator, determines if they are in the page resources, and adds in the relative location before the image source. I would recommend limiting the scope of this to a specific page type where needed.

This code is fairly brittle but works for my narrow use case. I’m not strong in Go and fairly new to Hugo so let me know if this can be improved. :slight_smile:

<section class="container page">
   <article>
     <header>
       <h1>{{ .Title }}</h1>
     </header>
     <div class="container gallery">
       {{ $imgs := findRE "src=\"(.*?)\"" .Content }}
       {{ $link := replace .Permalink .Site.BaseURL "" }}
       {{ $resources := .Resources }}
       {{ $scratch := newScratch }}
       {{ $scratch.Set "Content" .Content }}

       {{ range $imgs }}
           {{ $imgRef := strings.TrimRight "\"" (substr . 5) }}
           {{ if $resources.Match $imgRef }}
               {{ $replace := $imgRef | printf "%s%s" $link }}
               {{ $scratch.Set "Content" (replace (string ($scratch.Get "Content")) $imgRef $replace) }}
           {{ end }}
       {{ end }}
       {{ safeHTML ($scratch.Get "Content") }}
     </div>
   </article>
 </section>