anoop chandran
anoop chandran

Reputation: 1500

How to access json data file for all svelte components in sapper/polka

I'm trying to rewrite my website(Pug+Express) in Sapper(sveltejs). I'm a beginner in sveltejs , so kindly excuse if my question may come out really naive.
I have a template.json file that contains all the static data of my website. In the expressjs version I do const template = require('template.json') and render the page using pug template something like this

router.get('/:pageName', function(req, res, next) {
  res.render('pages/About', {template: template})

What would be an equivalent version of achieving this in sveltejs/sapper? So far I did an import template from 'template.json' in app/server.js file. Then what? Since the sapper-template is using polka instead of express, I'm confused how to get it right.Any suggestions?

Upvotes: 1

Views: 3487

Answers (1)

Rich Harris
Rich Harris

Reputation: 29605

You'd put that data in the pages (i.e. components in routes) that use it:

<!-- routes/index.html -->
<h1>{{title}}</h1>

<script>
  import data from './_template.json';

  export default {
    data() {
      return {
        title: data.title
      };
    }
  };
</script>

Note that I've added an underscore to _template.json, to hide the file from the router — you could also just place the JSON file outside the routes directory.

You can use Express instead of Polka; just npm install express and replace every occurrence of polka in app/server.js with express.

Upvotes: 5

Related Questions