【问题标题】:Using Sapper, How to get the current page's slug in template.html使用 Sapper,如何在 template.html 中获取当前页面的 slug
【发布时间】:2021-06-18 17:24:11
【问题描述】:

浏览文档,Sapper 的 template.html 似乎只有这些标签可用:

%sapper.base%
%sapper.styles%
%sapper.head%
%sapper.html%
%sapper.scripts

我想要的是当前页面的 slug 可以像这样使用它:

  <!-- bottom of template.html -->

  <img src="https://piratepx.com/page={currentPageSlug}" 
    alt="" style="display:none;"/>
</body>
</html>

不需要JS可以使用,在HTML中添加即可。

我正在导出到静态,这对于大多数静态站点生成器来说都是一项微不足道的任务,但我找不到 Sapper 的明显解决方案。

【问题讨论】:

  • 是什么阻止你在 Svelte 中添加它?
  • 没什么,但我必须将它添加到每一页而不是一次。另外,我宁愿让那个图像标签不由 JS 呈现,只是 HTML。听起来您已经知道如何将其做得相当好……请随时回答!

标签: svelte-3 sapper


【解决方案1】:

考虑到您正在使用 Sapper,我会在 _layout.svelte 中执行此操作:

<script>
 import { stores } from '@sapper/app';
 const { page } = stores();
 $: currentPageslug = $page.params.slug
</script>

<img src="https://piratepx.com/page={currentPageSlug}" alt=""/>

使用这种技术,您还可以添加默认值,或者在没有 slug 的情况下添加一些条件。

【讨论】:

  • 它在 _layout.svelte 中不起作用,但我在页脚中应用了相同的逻辑并且它有效,即使禁用了 JS。谢谢!
猜你喜欢
  • 2021-02-25
  • 2021-05-04
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 2019-11-13
相关资源
最近更新 更多