Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Content & Markdown

?How To add alt information to this twig?

Solved by pamtbaau View solution

Started by Jason 6 years ago · 2 replies · 1606 views
6 years ago

I'm using grav-skeleton-blog-site templates. Everything is going well except for one small SEO suggestion. The blog page displays recent items using blog-list-item-html-twig

This twig line: <a aria-label="link to {{ page.title }} article" href="{{ page.url }}">{{ image.cropZoom(800,400).html|raw }}</a>

creates this HTML: <a aria-label="link to Congratulations to the High School Class of 2020 article" href="/articles/congratulations-to-the-high-school-class-of-2020"><img alt="" src="/images/7/e/0/9/9/7e099ac3c7a5f83a7fd345bc6b11031f571ce79f-congratulations-to-the-class-of-2020.jpeg"></a>

How do I get info into the alt=""?

Thanks,
J

6 years ago Solution

@unleashed, Meta data of an image can be stored in a separate meta file, which has the same name as the image, but extended with .meta.yaml. In your case that would be congratulations-to-the-class-of-2020.jpeg.meta.yaml. This file is stored in the same folder as the image.

In that file you can add any yaml you like. For example:

YAML
title: Title of the image
alt: Alt text of image

In Twig, this meta data can be accessed using image.meta.title

The Grav method Media::html() has a few parameters among which 'title' and 'alt'
In template '/templates/partials/blog-list-item.html.twig' you can now add these parameters to the Medium::html() function.

Replace:

TWIG
<a href="{{ page.url }}">{{ image.cropZoom(800,400).html|raw }}</a>

with:

TWIG
<a href="{{ page.url }}">{{ image.cropZoom(800,400).html(image.meta.title, image.meta.alt)|raw }}</a>

Important note: When changing files (eg. a template) in a theme, these changes will be lost when a new release of the theme is installed. Therefor, you should make these changes in a so called inherited theme.

last edited 05/22/20 by pamtbaau
6 years ago

Thank you that worked!

Cheers,
J

p.s.
FWIW, I would prefer not to create a new meta file for each article image. Instead I added alt: 'my alt text' to the page header and used the existing header title.

TWIG
    <a aria-label="link to {{ page.title }} article" href="{{ page.url }}">{{ image.cropZoom(800,400).html(page.header.title, page.header.alt)|raw }}</a>
last edited 05/22/20 by Jason

Suggested topics

Topic Participants Replies Views Activity
Content & Markdown · by Jochen, 8 months ago
6 100 8 months ago
Content & Markdown · by Ton Haarmans, 1 year ago
10 187 1 year ago
Content & Markdown · by Jan L'Am, 1 year ago
4 148 1 year ago
Content & Markdown · by Leonardo, 1 year ago
3 63 1 year ago
Content & Markdown · by belthasar, 1 year ago
4 259 1 year ago