@11tyrocks/eleventy-plugin-social-images 中文文档教程

发布于 3年前 浏览 22 项目主页 更新于 3年前

Eleventy Plugin: Social Images

动态生成的社交媒体图像。

该软件包根据您的可用页面创建适合社交媒体标签(特别是 Twitter 和 Facebook)大小的动态图像。 使用一种预定义的颜色主题,或定义您自己的样式、模板或两者来自定义布局。

配置 CLI 脚本以在 Eleventy 构建之后运行,默认情况下图像将在 _site/previews/ 中创建为 png 图像。 使用 CLI 选项定义自定义 outputDir 和/或自定义 imageDir

这些图像在您的输出目录中创建,因为该过程在 Eleventy 构建完成后运行。

用于屏幕截图的窗口大小为 600 像素宽 x 315 像素高(然后以 2 倍分辨率保存),如果您选择创建自定义模板和样式,您可以使用它来测试它们。

??? 如果您发现问题,请添加问题。 这已经在本地构建和 Netlify 中进行了测试,但需要社区进行更广泛的测试。 感谢贡献者

Usage

首先,安装包:

npm install @11tyrocks/eleventy-plugin-social-images

使用这个包需要三个步骤

  1. Setup the command line script and add it to your Eleventy build
  2. Generate a JSON file containing data for each page you want social images
  3. Include a reference to the image in your templates

如果你使用的是持续集成的主机(比如 Netlify),你还需要修改构建您提供给主机的脚本以添加以下内容并确保 Chrome headless 成功启动以供管道中的 Puppeteer 使用:

AWS_LAMBDA_FUNCTION_NAME=trickpuppeteer npm run build

Setup the CLI Script

从技术上讲,此软件包提供了一个插件组件,但大部分功能是通过调用命令行脚本添加的。

cli 脚本的最低设置是:

eleventy-social-images --siteName 'Your Site Name'

建议构建用于生产的 Eleventy 后添加这个,以减少在 serve 模式下对系统的压力,例如通过添加以下内容在您的 package.json 中:

"scripts": {
  "social-images": "eleventy-social-images --siteName 'Your Site Name'",
  "start": "eleventy --serve",
  "build": "eleventy ; npm run social-images"
}

Setup the Page Data JSON

Eleventy 插件本身仅提供一个可选 过滤器来帮助在所需的 JSON 文件中格式化标题。

该过滤器称为 addNbsp,它会在标题的最后两个单词之间插入一个不间断空格 - nbsp;,以防止在最后一行悬空一个单词 (被打字员称为“孤儿”)。

请参阅下一节了解如何添加插件

要创建所需的页面数据 JSON,这里有一个起始模板,它循环遍历 all 集合并包含两个预期的键:titleimgName .

重要:请务必将 pages.json 文件的完整路径添加到 .gitignore.eleventyignore当 Eleventy 处于 --serve 模式时防止无限循环。

  • This should be created as a Nunjucks template, ex. pagesjson.njk so that it is recognized by Eleventy for processing.
  • Place this either at the root of your input directory, or in a custom directory in your input folder (ex. _generate).
  • Note the unique frontmatter, which essentially mean "do not include this in the normal site output".
  • If you have customized your input directory via your Eleventy config, you may want to change the permalink value because it is relative to your project root, not the directory where it is placed.
  • The example uses the addNbsp filter which is optional - see the next section for how to include the plugin and gain access to that filter.
  • When the addNbsp filter is used, you must also include safe to allow the nbsp; to be successfully included.
  • slug is a built-in Eleventy filter that will for example transform 'Hello World' into 'hello-world'
---
permalink: "./pages.json"
permalinkBypassOutputDir: true
eleventyExcludeFromCollections: true
---
[
{%- for pages in collections.all %}
  {
      "title":"{{ pages.data.title | addNbsp | safe }}",
      "imgName":"{{ pages.data.title | slug }}"
  }{% if loop.last == false %},{% endif -%}
{% endfor %}
]

您可以根据自己的命名约定和永久链接结构修改用作值的内容。 您可能需要将其范围限定为特定集合而不是 all查看关于集合的 11ty 文档 >

Custom template variables

在 v0.3.0 中添加 - 包括额外的变量传递到自定义模板中,例如:

[
{%- for pages in collections.all %}
  {
      "title":"{{ pages.data.title | addNbsp | safe }}",
      "imgName":"{{ pages.data.title | slug }}",
      "variables": {
        "postdate": "{{ pages.data.postdate }}"
        {%- if pages.data.description %},
        "description": "{{ pages.data.description }}"
        {% endif %}
      }
  }{% if loop.last == false %},{% endif -%}
{% endfor %}
]

通过将数据属性添加到应包含变量值的元素,在您的模板中使用。 例如

不可用的变量只会产生空元素。 如果您发现空元素正在影响您的模板样式,请使用 :empty 选择器通过 CSS 删除它们,例如 p:empty { display: none }

您希望 postdate 出现的位置。

感谢 Thomas Michael Semmler 启动了变量 功能!

如前所述,该插件启用 addNbsp 过滤器。

Optional: Add the Plugin

在您的 11ty 项目中安装插件:

然后,将其包含在您的 .eleventy.js 配置文件中:

最后一步由您决定,即将您首选服务的社交媒体标签放在 <您的 Eleventy 模板的代码>。

const socialImages = require("@11tyrocks/eleventy-plugin-social-images");

module.exports = (eleventyConfig) => {
  eleventyConfig.addPlugin(socialImages);
};

Add image references in your templates

以下是包含 Twitter 和 Facebook 图像的 Nunjuck 示例 - 两者都需要额外的标签才能实现完整的社交共享功能。 查看我的 11ty Netlify Starter 以获得这些服务的完整标签。

请注意,编译后的图像 URL 需要是完整的、绝对 URL 才能正确用于社交服务。 在这个例子中,取自我的 11ty Netlify Jumpstart,meta.url 是在 _data/meta.js 中定义的,例如:

{%- set pageSocialImg %}{{ meta.url }}/previews/{{ title | slug }}.png{% endset
-%}
<meta property="og:image" content="{{pageSocialImg}}" />
<meta name="twitter:image" content="{{pageSocialImg}}" />

其中 env.URL 由 Netlify 在构建时提供。 您的主机可能会提供类似的选项,或者您可以选择将您的实时 URL 硬编码到标签中。

module.exports = {
  url: process.env.URL || "http://localhost:8080",
};

默认设置为假定 Eleventy 构建默认值。 因此,图像将在 _site/previews/ 中创建为 png 图像,并期望您的 pages.json 位于项目根目录中。

CLI Config Options

OptionTypeDefault
siteNamestring11ty Rocks!
outputDirstring_site
imageDirstringpreviews
dataFilestringpages.json
templatePathstring
stylesPathstring
themeenum: 'blue' | 'green' | 'minimal' | 'sunset' | 'pop'blue
widthnumber600
heightnumber315
deviceScaleFactornumber2

Config Examples

如果您设置了自定义 output 目录,则还要更新 outputDir,例如:--outputDir public

Custom output directory

预览预定义的主题 >

Define theme to use

要从其中一个预定义的主题中选择,通过 --theme [themename] 其中 themename 是以下之一:

默认情况下,此插件将创建 600px 宽和 315px 高的社交图像。 要选择不同的尺寸,请传递 --width--height 参数,例如 --width 1280 --height 720

  • blue (default)
  • green
  • minimal
  • sunset
  • pop

Custom image dimensions

默认设备比例因子(或设备像素比)为 2,模拟高- 每英寸点数/Retina 显示屏。 要更改设备比例因子,您可以传递---deviceScaleFactor,如--deviceScaleFactor 1

要为您的图像定义另一个名称,请传递目录名称​​而不 输出路径,例如:--imageDir img

Custom preview directory to output images

提醒:图像在您的输出目录中创建,因为该过程在 Eleventy 构建完成后运行。

要使用您自己的样式表,请在项目的任意位置创建一个 CSS 文件。 然后,传递像 --stylesPath social/style.css 这样的路径。

Custom style

然后将使用您的样式表而不是默认样式表。

关于网络字体的注意事项:为了确保为屏幕截图加载网络字体获得最佳效果,请在样式表中使用 CSS @import 选项。

要使用您自己的模板,请在您的项目中创建一个 html 文件。 您可能希望通过将其添加到 .eleventyignore 将其放在自定义输入目录之外,将其从 Eleventy 中排除以防止将其构建为页面。

Custom template

然后,传递像 --templatePath social/template.html 这样的路径。

然后将使用您的模板而不是默认模板。

请参阅自定义模板变量,了解如何启用额外的模板数据。

您必须包含一个 h1 用作替换内容标题的挂钩。 模板的其余部分由您决定!

Important notes on custom templates

包含以下内容以便样式表可以注入到模板中:

如果您不是自定义整个样式表但想更改其中的一部分,例如 h1 大小,您可以在 {{ style }} 之后添加该单一样式以覆盖默认值,这要归功于 CSS 级联。

<style>
  {{ style }}
</style>

要使用自定义模板但继续使用预定义的主题,请在 上添加一个 class 值,其中包含您喜欢的主题值。

您可以通过定义两个 CLI 选项来传递自定义模板和样式表,例如。 --templatePath social/template.html --stylesPath social/style.css

Custom template and style

由于这个完整的示例包含样式,因此唯一缺少的选项是 theme,因为它不会产生额外的效果。

Fully customized example

如果您使用 WSL,则需要一个浏览器。 通过执行以下操作在 WSL 中安装 chrome:

eleventy-social-images --siteName 'My Cool Site' --outputDir public --dataFile src/_generate/pages.json --imageDir imgs --templatePath social/template.html --stylesPath social/style.css --width 1280 --height 720 --deviceScaleFactor 1

WSL

您可以通过执行 google-chrome --version 来确认这是否有效。

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt -y install ./google-chrome-stable_current_amd64.deb

嗨 - 我是 Stephanie Eckles (@5t3ph),11ty.Rocks< 的创建者/a> 和在那里编译的其他资源。

Colophon

如果您喜欢我的工作并使用我的项目,请考虑请我喝咖啡

这个插件最初是对我的解决方案的改编 在这篇博文中有详细介绍 并包含在我的 11ty Netlify Jumpstart 中。 它在我基于 11ty 的网站上得到积极使用:

包含的渐变主题灵感来自 uiGradients

Credits

The included gradient themes inspired by uiGradients

Contributors

Eleventy Plugin: Social Images

Dynamically generated social media images.

This package creates dynamic images sized for social media tags (particularly Twitter and Facebook) based on your available pages. Use one of the predefined color themes, or define your own style, template, or both to customize the layout.

Configure the CLI script to run after your Eleventy build, and by default images will be created in _site/previews/ as png images. Use the CLI options to define a custom outputDir and/or a custom imageDir.

The images are only created in your output directory since the process runs after the Eleventy build is complete.

The window size used for the screenshot is 600px wide by 315px tall (which is then saved at 2x resolution) which you can use to test your template and styles if you choose to create them custom.

???? If you find a problem please add an issue. This has been tested on local builds and within Netlify, but needs broader tests by the community. Thanks to the contributors!

Usage

First, install the package:

npm install @11tyrocks/eleventy-plugin-social-images

There are three steps to using this package:

  1. Setup the command line script and add it to your Eleventy build
  2. Generate a JSON file containing data for each page you want social images
  3. Include a reference to the image in your templates

If you're using a host with continuous integration (like Netlify) you will also need to amend the build script you provide to your host to add the following and ensure Chrome headless is successfully launched for use by Puppeteer in the pipeline:

AWS_LAMBDA_FUNCTION_NAME=trickpuppeteer npm run build

Setup the CLI Script

Technically, this package offers a plugin component, but most of the functionality is added by calling the command line script.

The minimum setup for the cli script is:

eleventy-social-images --siteName 'Your Site Name'

It's recommended to add this after building Eleventy for production to reduce strain on your system when in serve mode, for example by adding the following in your package.json:

"scripts": {
  "social-images": "eleventy-social-images --siteName 'Your Site Name'",
  "start": "eleventy --serve",
  "build": "eleventy ; npm run social-images"
}

Setup the Page Data JSON

The Eleventy plugin itself is only providing an optional filter to help format titles within the required JSON file.

The filter is called addNbsp and it inserts a non-breaking space - nbsp; - between the last two words in the title to prevent a single word dangling on the last line (called an "orphan" by typographers).

See the next section for how to add the plugin.

To create the required page data JSON, here is a starting template that loops through the all collection and includes the two expected keys: title and imgName.

Important: Be sure to add the full path of your pages.json file to either .gitignore or .eleventyignore to prevent an infinite loop when Eleventy is in --serve mode.

  • This should be created as a Nunjucks template, ex. pagesjson.njk so that it is recognized by Eleventy for processing.
  • Place this either at the root of your input directory, or in a custom directory in your input folder (ex. _generate).
  • Note the unique frontmatter, which essentially mean "do not include this in the normal site output".
  • If you have customized your input directory via your Eleventy config, you may want to change the permalink value because it is relative to your project root, not the directory where it is placed.
  • The example uses the addNbsp filter which is optional - see the next section for how to include the plugin and gain access to that filter.
  • When the addNbsp filter is used, you must also include safe to allow the nbsp; to be successfully included.
  • slug is a built-in Eleventy filter that will for example transform 'Hello World' into 'hello-world'
---
permalink: "./pages.json"
permalinkBypassOutputDir: true
eleventyExcludeFromCollections: true
---
[
{%- for pages in collections.all %}
  {
      "title":"{{ pages.data.title | addNbsp | safe }}",
      "imgName":"{{ pages.data.title | slug }}"
  }{% if loop.last == false %},{% endif -%}
{% endfor %}
]

You may modify what is used as the values based on your own naming convention and permalink structure. You may need to scope it to a particular collection vs. all. Check out the 11ty docs on collections >

Custom template variables

Added in v0.3.0 - include additional variables to pass into a custom template, such as:

[
{%- for pages in collections.all %}
  {
      "title":"{{ pages.data.title | addNbsp | safe }}",
      "imgName":"{{ pages.data.title | slug }}",
      "variables": {
        "postdate": "{{ pages.data.postdate }}"
        {%- if pages.data.description %},
        "description": "{{ pages.data.description }}"
        {% endif %}
      }
  }{% if loop.last == false %},{% endif -%}
{% endfor %}
]

Use in your template by adding data attributes to elements that should contain the variable value. For example <p data-postdate></p> where you want the postdate to appear.

Unavailable variables will simply produce empty elements. If you find the empty elements are impacting your template styles, remove them via CSS with the :empty selector, ex p:empty { display: none }.

Kudos to Thomas Michael Semmler for initiating the variables functionality!

Optional: Add the Plugin

As noted previously, the plugin enables the addNbsp filter.

Install the plugin in your 11ty project:

Then, include it in your .eleventy.js config file:

const socialImages = require("@11tyrocks/eleventy-plugin-social-images");

module.exports = (eleventyConfig) => {
  eleventyConfig.addPlugin(socialImages);
};

Add image references in your templates

The final step is up to you, which is placing the social media tags for you preferred services in the <head> of your Eleventy templates.

Here are Nunjuck examples of including the image for both Twitter and Facebook - both of which require additional tags for full social share functionality. Check out my 11ty Netlify Starter for full tags for these services.

{%- set pageSocialImg %}{{ meta.url }}/previews/{{ title | slug }}.png{% endset
-%}
<meta property="og:image" content="{{pageSocialImg}}" />
<meta name="twitter:image" content="{{pageSocialImg}}" />

Note that the compiled image URL needs to be a full, absolute URL in order to work correctly for the social services. In this example, taken from my 11ty Netlify Jumpstart, meta.url is defined in _data/meta.js, such as:

module.exports = {
  url: process.env.URL || "http://localhost:8080",
};

Where the env.URL is provided by Netlify at build time. Your host may offer a similar option, or you may choose to hardcode your live URL into the tag.

CLI Config Options

OptionTypeDefault
siteNamestring11ty Rocks!
outputDirstring_site
imageDirstringpreviews
dataFilestringpages.json
templatePathstring
stylesPathstring
themeenum: 'blue' | 'green' | 'minimal' | 'sunset' | 'pop'blue
widthnumber600
heightnumber315
deviceScaleFactornumber2

Config Examples

The defaults are setup to assume Eleventy build defaults. So, the images will be created in _site/previews/ as png images, and expect your pages.json to live at the project root.

Custom output directory

If you have set a custom output directory, then also update outputDir, ex: --outputDir public.

Define theme to use

Preview the predefined themes >

To select, from one of the predefined themes, pass --theme [themename] where themename is one of the following:

  • blue (default)
  • green
  • minimal
  • sunset
  • pop

Custom image dimensions

By default, this plugin will create social images that are 600px wide and 315px tall. To choose different dimensions, pass --width and --height arguments, as in --width 1280 --height 720.

The default device scale factor (or device pixel ratio) is 2, emulating high-dots-per-inch/Retina displays. To change the device scale factor, you can pass ---deviceScaleFactor, as in --deviceScaleFactor 1.

Custom preview directory to output images

To define another name for your images to live, pass the directory name without the output path, ex: --imageDir img.

Reminder: The images are only created in your output directory since the process runs after the Eleventy build is complete.

Custom style

To use your own stylesheet, create a CSS file anywhere in your project. Then, pass the path like --stylesPath social/style.css.

Your stylesheet will then be used instead of the default one.

Note on web fonts: For best results ensuring the web font loads for the screenshot, use the CSS @import option within your stylesheet.

Custom template

To use your own template, create an html file in your project. You may want to exclude it from Eleventy to prevent it being built as a page by adding it to .eleventyignore or placing it outside of your customized input directory.

Then, pass the path like --templatePath social/template.html.

Your template will then be used instead of the default one.

Refer back to custom template variables for how to enable additional template data.

Important notes on custom templates

You must include an h1 to be used as the hook to replace the title of the content. The rest of the template is up to you!

Include the following so that the stylesheet can be injected into the template:

<style>
  {{ style }}
</style>

If you are not customizing the entire stylesheet but would like to alter part of it, such as the h1 size, you can add that singular style after {{ style }} to override the defaults thanks to the CSS cascade.

To use a custom template but keep using a predefined theme, add a class value on <body> with your preferred theme value.

Custom template and style

You can pass both a custom template and stylesheet by defining both CLI options, ex. --templatePath social/template.html --stylesPath social/style.css.

Fully customized example

Since this full example includes style, the only option missing is theme since it would have no additional effect.

eleventy-social-images --siteName 'My Cool Site' --outputDir public --dataFile src/_generate/pages.json --imageDir imgs --templatePath social/template.html --stylesPath social/style.css --width 1280 --height 720 --deviceScaleFactor 1

WSL

If you use WSL, you'll need a browser. Install chrome in WSL by doing:

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt -y install ./google-chrome-stable_current_amd64.deb

You can confirm this worked by doing google-chrome --version.

Colophon

Hi - I'm Stephanie Eckles (@5t3ph), creator of 11ty.Rocks and the other resources compiled there.

If you enjoy my work and use my projects, please consider buying me a coffee.

This plugin is an adaptation for my solution originally detailed in this blog post and included in my 11ty Netlify Jumpstart. It's in active use on my 11ty-based sites:

Credits

The included gradient themes inspired by uiGradients

Contributors

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文