Giter VIP home page Giter VIP logo

eleventy-plugin-sitemap's Introduction

eleventy-plugin-sitemap

npm Release workflow Test workflow codecov semantic-release Commitizen friendly License: MIT

Eleventy plugin to generate a sitemap using ekalinin/sitemap generator.

Installation

Install the package:

npm install --save @quasibit/eleventy-plugin-sitemap

Add the plugin to your Eleventy configuration (usually .eleventy.js):

const sitemap = require("@quasibit/eleventy-plugin-sitemap");

module.exports = function(eleventyConfig) {
  eleventyConfig.addPlugin(sitemap, {
    sitemap: {
      hostname: "https://example.com",
    },
  });
};

Usage

Create a sitemap file and use the shortcode to generate the sitemap XML:

---
permalink: /sitemap.xml
layout: null
eleventyExcludeFromCollections: true
---
{% sitemap collections.all %}

The above snippet does the following:

  • Sets the permalink to /sitemap.xml.
  • Disables any layout.
  • Excludes the sitemap file from Eleventy collections.
  • Calls the sitemap shortcode.

As the first argument to the shortcode, you pass the collection of items that you want to use in the sitemap.

This shortcode is available for Liquid, Nunjucks, and Javascript templates.

You can also copy this sample from the examples and adapt it to your needs:

cp node_modules/@quasibit/eleventy-plugin-sitemap/examples/default/sitemap.njk sitemap.njk

After creating the sitemap, you should add the sitemap to robots.txt:

Sitemap: https://example.com/sitemap.xml

Options

The following options are available:

eleventyConfig.addPlugin(sitemap, {
  // Name of the property for the last modification date.
  // By default it is undefined and the plugin will fallback to `date`.
  // When set, the plugin will try to use this property and it will fallback
  // to the `date` property when needed.
  lastModifiedProperty: "modified",

  sitemap: {
    // Options for SitemapStream. See https://github.com/ekalinin/sitemap.js/blob/master/api.md#sitemapstream
    // Hostname is needed when the URLs of the items don't include it.
    hostname: "https://example.com",
  },
});

Examples

See ./examples folder.

Advanced usage

Customizing sitemap properties

You can customize the values used for the sitemap links by adding front matter to your pages.

---
sitemap:
  changefreq: weekly
  priority: 0.8
---

Alternatively, you can apply the properties to a folder of items by creating a directory data file.

Assuming you want to apply this to all the files in posts/*:

// posts/posts.11tydata.js
module.exports = () => {
  return {
    sitemap: {
      changefreq: "weekly",
      priority: 0.8,
    },
  }
}

For a full list of options, please refer to Sitemap Item Options.

Exclude pages from the sitemap

You have several options to exclude pages from the sitemap.

You can exclude them using the standard eleventyExcludeFromCollections property, which will exclude them from all collections.

---
eleventyExcludeFromCollections: true
---

You can use the ignore property on the sitemap data, which will only exclude it from the sitemap.

---
sitemap:
  ignore: true
---

Or you can create a custom collection that excludes the items that you don't want in the sitemap and then pass that collection to the shortcode.

eleventyConfig.addCollection("sitemap", function(collectionApi) {
  return collectionApi.getAll().filter(item => {
    // Place your condition here for excluding items from the sitemap.
    return true;
  });
});

Specify the collection in the shortcode:

{% sitemap collections.sitemap %}

Create a multilingual sitemap

For creating a multilingual sitemap you need to add alternate language child links for each link.

You could do this with front matter and the links property , but in most cases it's easier to do this with a custom collection.

eleventyConfig.addCollection("sitemap", function(collectionApi) {
  return collectionApi
    .getAll()
    .map((item, index, all) => {
      return {
        url: item.url,
        date: item.date,
        data: {
          ...item.data,
          sitemap: {
            ...item.data.sitemap,
            links:
              all
                // Find all the translations of the current item.
                // This assumes that all translated items that belong together
                // have the same `translationKey` value in the front matter.
                .filter(other => other.data.translationKey === item.data.translationKey)

                // Map each translation into an alternate link. See https://github.com/ekalinin/sitemap.js/blob/master/api.md#ILinkItem
                // Here we assume each item has a `lang` value in the front
                // matter. See https://support.google.com/webmasters/answer/189077#language-codes
                .map(translation => {
                  return {
                    url: translation.url,
                    lang: translation.data.lang,
                  };
                }),
          },
        },
      }
    });
});

And then pass that collection to the sitemap shortcode:

{% sitemap collections.sitemap %}

You can see an example with dynamic hostnames in ./examples/multilingual/.

Related plugins

Maintainers

License

MIT. See LICENSE.

eleventy-plugin-sitemap's People

Contributors

dependabot[bot] avatar nunof07 avatar ovlb avatar revelt avatar rq-abrahamsson avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

eleventy-plugin-sitemap's Issues

Closing xml tag not being generated.

My config is

  eleventyConfig.addPlugin(sitemap, {
    sitemap: {
      hostname: hostname,
    },
  });

And my sitemap file is

---
permalink: /sitemap.xml
layout: null
eleventyExcludeFromCollections: true
---
{% sitemap collections.all %}

The result looks great except for it's missing the closing XML tag. Like this

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
	xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
	xmlns:xhtml="http://www.w3.org/1999/xhtml"
	xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
	xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
	<url>
		...
	</url>
        ...
</urlset>

Any ideas what would cause the missing xml close tag?

How to exclude specific files from the sitemap (sorry for insisting)

How do i exclude specific files from the sitemap, that don't have front matter, like "footer"? I'm a self taught programmer and I have no idea what to do with the information that's on the docs.

eleventyConfig.addCollection("sitemap", function(collectionApi) {
return collectionApi.getAll().filter(item => {

// Place your condition here for excluding items from the sitemap. --> What condition? What do i put here if i want to remove the footer.njk and other files? 

return true;

});
});

Thank you for your time.

Fetching collections with data files

Hi,
I'm API fetching three collections using three different data files. When I try {% sitemap datafile %} I'm getting an error EmptySitemap: You ended the stream without writing anything.

Is there a way to use your plugin with such configuration, where collections are not coming from folders nor as custom collections defined in .eleventy.js?

Cheers.

Multilingual sitemap not rendered correctly

I have implemented this plugin on my website, and the sitemap is correctly generated. Nevertheless, no alternate links are working.

  1. I installed the plugin and configured it
  2. I set the default lang as en, for all pages. Doing so, I would need to specify only languages ≠ en
  3. I created the custom collection, only changing translationKey with ref
  4. I created sitemap.njk, but…
  5. https://tommi.space/sitemap.xml contains no alternate pages.

What am I doing wrong?

Thanks a lot in advance!

Best,
Tommi

eleventyComputed value for sitemap.ignore

I am pulling data in from Contenful. All works fine, I can render data onto the page and the correct values appear. My problem is with pushing this data through to your Site Map. Please can you see if this is something dumb on my part. I have a boolean field called includeInSiteMap.

---
layout: contained.njk
pagination:
  data: dunbar
  size: 1
  alias: dunbarPage
permalink: "{{ dunbarPage.slug | safeSlug }}"
eleventyComputed:
  sitemap:
    ignore: "{{ not dunbarPage.includeInSiteMap }}"
---
:
<h3>{{ not dunbarPage.includeInSiteMap }}</h3>

The value in the h3 is always reflective of the value passed in, however the sitemap is not. If I hardwire true or false in the sitemap.ignore line it works absolutely fine.

Its like its building the Site Map before the value is resolved in the Front Matter. Any clues would be appreciated, thank you so much.

eleventy 0.11.0 dependency error

This is most likely user error, but I am receiving a dependency error whilst trying to install eleventy-plugin-sitemap.

npm ERR! Found: @11ty/[email protected]
npm ERR! node_modules/@11ty/eleventy
npm ERR!   dev @11ty/eleventy@"^0.12.1" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @11ty/eleventy@"^0.11.0" from @quasibit/[email protected]
npm ERR! node_modules/@quasibit/eleventy-plugin-sitemap
npm ERR!   dev @quasibit/eleventy-plugin-sitemap@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry

Paginated archive

See #19 (comment)

Paginated pages with many posts per page don't have all entries in sitemap and pagination numbers are not included in URLs.

Invalid URL errror when generating sitemap.

Hello.

I was trying the plugin, but when I run build, it fails with the following error and have no idea if I am doing something wrong.

> (./src/sitemap.njk)
  EleventyShortcodeError: Error with Nunjucks shortcode `sitemap`

`Template render error` was thrown
> Invalid URL: /

`Template render error` was thrown:
    TypeError [ERR_INVALID_URL]: Invalid URL: /
        at onParseError (internal/url.js:259:9)
        at new URL (internal/url.js:335:5)
        at Object.normalizeURL (/home/bruno/Code/Playground/eleventy-template/node_modules/sitemap/dist/lib/utils.js:274:15)
        at SitemapStream._transform (/home/bruno/Code/Playground/eleventy-template/node_modules/sitemap/dist/lib/sitemap-stream.js:77:65)
        at SitemapStream.Transform._read (internal/streams/transform.js:205:10)
        at SitemapStream.Transform._write (internal/streams/transform.js:193:12)
        at writeOrBuffer (internal/streams/writable.js:358:12)
        at SitemapStream.Writable.write (internal/streams/writable.js:303:10)
        at sitemap (/home/bruno/Code/Playground/eleventy-template/node_modules/@quasibit/eleventy-plugin-sitemap/src/sitemap.js:21:12)
        at Object.getSitemap (/home/bruno/Code/Playground/eleventy-template/node_modules/@quasibit/eleventy-plugin-sitemap/.eleventy.js:19:12)
Copied 1 file / Wrote 0 files in 0.17 seconds (v0.12.1)

I just have a simple site with an index and about pages.

Using Eleventy 0.12.1.

This plugin causes a build fail

I've tried adding this to two different projects, and even a template, and I always get the same build fail... I'm using the provided template.

# npm start

> start
> npx @11ty/eleventy --quiet --serve

[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] > Having trouble rendering njk template ./src/sitemap.njk

`TemplateContentRenderError` was thrown
[11ty] > (./src/sitemap.njk) [Line 2, Column 4]
  unknown block tag: sitemap

`Template render error` was thrown:
[11ty]     Template render error: (./src/sitemap.njk) [Line 2, Column 4]
      unknown block tag: sitemap
        at Object._prettifyError (/mnt/site/node_modules/nunjucks/src/lib.js:36:11)
        at Template.init (/mnt/site/node_modules/nunjucks/src/environment.js:511:19)
        at Template.Obj (/mnt/site/node_modules/nunjucks/src/object.js:62:15)
        at new Template (/mnt/site/node_modules/nunjucks/src/environment.js:478:18)
        at Nunjucks.compile (/mnt/site/node_modules/@11ty/eleventy/src/Engines/Nunjucks.js:479:14)
        at Html.compile (/mnt/site/node_modules/@11ty/eleventy/src/Engines/Html.js:16:28)
        at TemplateRender.getCompiledTemplate (/mnt/site/node_modules/@11ty/eleventy/src/TemplateRender.js:238:26)
        at Template.compile (/mnt/site/node_modules/@11ty/eleventy/src/TemplateContent.js:294:42)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async Template._render (/mnt/site/node_modules/@11ty/eleventy/src/TemplateContent.js:388:16)
[11ty] Wrote 0 files in 0.14 seconds (v1.0.0)

Automatically change page sitemap information according to specific post metadata

Suppose I have many work in progress pages containing the wip tag. Such pages, as long as they are labelled with this tag, are likely to change more frequently, and, since they are incomplete, they should have a lower priority.

How could I set arbitrary values e.g. for changefreq and priority according to whether a page has the a certain tag or a certain front-matter value?

How to automatically detect the page image

Currently, the plugin natively supports no image linking. In my website, in the front matter of some pages I have an image string, containing its URL. Otherwise, I set a default fallback image. By doing so, I always have an image URL when using {{ image }} within each and every template.

How can I make this plugin recognize the image? If I use:

// tommi.space/content/content.11tydata.js
module.exports = {
  sitemap {
    img {
      url: '{{ image }}'
    }
  }
}

…it is printed https://tommi.space/%7B%7B%20image%20%7D%7D in the sitemap.

Could you help me? Thanks a lot! ❤️

[Question] Add custom URLs to the sitemap

Hey @nunof07, thanks for the awesome plugin.
I have a question about extending my sitemap with URLs from outside of my collections.all

Not sure it's best way to do that, but here is what I made.
sitemap.11ty.js:

module.exports = class {
  data() {
    return {
      layout: null,
      eleventyExcludeFromCollections: true,
      permalink: '/sitemap.xml',
    };
  }

  async render(data) {
    // save custom pages to array
    const customPages = [
      { url: '/innerUrl/pageOne/' },
      { url: '/innerUrl/pageTwo/' },
    ];
    // get URLs from collections.all
    const siteUrls = data.collections.all.map((item) => ({ url: item.url }));
    const sitemapUrls = siteUrls.concat(customPages);
    
    return await this.sitemap(sitemapUrls);
  }
};

this code is kinda working, but it's incredibly slow. My build is stuck on a step Writing build/sitemap.xml from ./src/sitemap.11ty.js. for more than 5 minutes before it's moving on. As I have a list of ~30 URLs, so it's too much for sitemap generation.

Can you help me to understand what am I doing wrong?

/about instead of /about.html

I set it up so that all my links are clean (= no .html). How can I have this plugin generate sitemap the same way?

Include in sitemap even if not in `collections.all`

I have a problem with Eleventy pages generation, and I really need to exclude from all collections my homepage. Nevertheless, by doing so, it gets excluded from the sitemap. It would be great to add support for:

sitemap:
  ignore: false

…in order to bypass eleventyExcludeFromCollections: true

The README instructions for advanced use are incorrect, resulting in the config being ignored

In the following sections of the README the usage instructions are incorrect:

https://github.com/quasibit/eleventy-plugin-sitemap#advanced-usage
https://github.com/quasibit/eleventy-plugin-sitemap#exclude-pages-from-the-sitemap

The example provided:

---
sitemap:
  - changefreq: weekly
  - priority: 0.8
---

Should actually be:

---
sitemap:
  changefreq: weekly
  priority: 0.8
---

The extra - change sitemap into an array of items which is not what the upstream sitemap lib expects. It expects changefreq and priority to be added as keys on an Object.

Without this change no changefreq or priority values are written into the generated sitemap.xml.

It might also be helpful to document how this config can be applied to a folder of items using e.g. blog.11tydata.js like:

module.exports = () => {
  return {
    layout: "post",
    tags: ["post"],
    sitemap: {
      changefreq: "weekly",
      priority: 0.8,
    },
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.