Search code examples
svelte-3sapper

Using Sapper, How to get the current page's slug in template.html


Going through the docs, it seems like Sapper's template.html only has these tags available:

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

What I'd love to have is the current page's slug to use it like so:

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

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

It doesn't need to be available to JS, just added in the HTML.

I'm exporting to static and this would be a trivial task with most Static Site Generators but I can't find the obvious solution with Sapper.


Solution

  • Considering you are using Sapper I would do this in _layout.svelte instead:

    <script>
     import { stores } from '@sapper/app';
     const { page } = stores();
     $: currentPageslug = $page.params.slug
    </script>
    
    <img src="https://piratepx.com/page={currentPageSlug}" alt=""/>
    

    With this technique you can also add a default value, or some condition in case there is no slug.