Helpers

# $url (path, params, strict)

  • path
    type: {String} (default value: ./ )
    Absolute, relative or named path.
  • params
    type: {Object} (default value: {} )
    Parameters to be parsed to the URL.
  • strict
    type: {Bool} (default value: false )
    Preserve "/index" at the end of an URL

$url resolves paths relative to the page/layout file in which it is used. This ensures consistent URLs which are unaffected by the current browser address (unlike normal relative URLs).

You can also call the function $url() on any page to get the current path.

<!-- src/pages/recipes/cakes/cupcakes.svelte --> <script> import { url } from '@sveltech/routify' //get current path console.log($url()) //'recipes/cakes/cupcakes' </script> <!-- relative --> <a href={$url('../../ingredients/sugar')}>Info about sugar</a> <!-- absolute --> <a href={$url('/ingredients/sugar')}>Info about sugar</a> <!-- named --> <a href={$url('sugar')}>Info about sugar</a> <!-- params --> <a href={$url('/users/:id', {id: '123'})}>Info author</a>
<!-- src/pages/recipes/cakes/cupcakes.svelte -->
<script>
  import { url } from '@sveltech/routify'

//get current path
console.log($url()) //'recipes/cakes/cupcakes'
</script>

<!-- relative -->
<a href={$url('../../ingredients/sugar')}>Info about sugar</a>

<!-- absolute -->
<a href={$url('/ingredients/sugar')}>Info about sugar</a>

<!-- named -->
<a href={$url('sugar')}>Info about sugar</a>

<!-- params -->
<a href={$url('/users/:id', {id: '123'})}>Info author</a>

If used in a component outside of a layout or page, the url will be relative to the layout or page which imports the component.

A named path is a path that doesn't start with . or /.

To name a page, add the name meta tag:<!-- routify:options name="blog" -->


# $isActive (path, strict)

  • path
    type: {String} (default value: ./ )
    Absolute, relative or named path.
  • strict
    type: {Bool} (default value: true )
    Preserve "/index" at the end of an URL

$isActive Checks if the provided path is part of the current route.

<!-- src/pages/_layout.svelte --> <script> import { isActive, url } from '@sveltech/routify' const links = [ ['./index', 'Home'], ['./about', 'About'], ['./contact', 'Contact'] ] </script> {#each links as [path, name]}} <a href={$url(path)} class:active={$isActive(path)}> {name} </a> {/each}
<!-- src/pages/_layout.svelte -->
<script>
  import { isActive, url } from '@sveltech/routify'

  const links = [
    ['./index', 'Home'],
    ['./about', 'About'],
    ['./contact', 'Contact']
  ]
</script>

{#each links as [path, name]}}
  <a href={$url(path)} class:active={$isActive(path)}>
    {name}
  </a>
{/each}

# $goto (path, params, static, shallow)

  • path
    type: {String} (default value: ./ )
    Parsed by the url helper.
  • params
    type: {Object} (default value: {} )
    Parsed by the url helper.
  • static
    type: {Boolean} (default value: false )
    Render URL without redirecting.
  • shallow
    type: {Boolean} (default value: false )
    Use the layouts of the goto's parent instead of the target.

Navigate programatically.

<script> import { goto } from '@sveltech/routify' $goto('../go/here') </script>
<script>
  import { goto } from '@sveltech/routify'
  $goto('../go/here')
</script>
For redirects, use the alias $redirect. This will omit the redirecting page from browser history.

# $params

    Use $params to access parameters from the URL.

    <!-- /user/:userId/posts/:postId --> <script> import { params } from '@sveltech/routify' console.log($params) /** {userId: 123, postId: 456} **/ </script>
    <!-- /user/:userId/posts/:postId -->
    <script>
      import { params } from '@sveltech/routify'
      console.log($params) /** {userId: 123, postId: 456} **/
    </script>

    By default, the query handler uses the native URLSearchParams function. For more advanced usage, you can create your own queryHandler . The queryHandler is an object with a parse and a stringify method.

    <script> ... import { parse, stringify } from 'qs' const queryHandler = { parse, stringify } </script> <Router config={{queryHandler}} ... />
    <script>
      ...
      import { parse, stringify } from 'qs'
      const queryHandler = { parse, stringify }
    </script>
    
    <Router config={{queryHandler}} ... />

    # $metatags ()

      Set metadata and Open Graph data for the current page.

      Please refer to Guide/metadata.


      # $page

        Returns the node of current page

        <!-- src/pages/_layout.svelte --> <script> import { page, metatags } from '@sveltech/routify' $: metatags.title = $page.title </script>
        <!-- src/pages/_layout.svelte -->
        <script>
          import { page, metatags } from '@sveltech/routify'
          $: metatags.title = $page.title
        </script>

        # $layout

          Returns the node of the current component

          <!-- src/pages/_layout.svelte --> <script> import { layout } from '@sveltech/routify' </script> {#each $layout.children as node} <a href="{node.path}">{node.title}</a> {/each}
          <!-- src/pages/_layout.svelte -->
          <script>
            import { layout } from '@sveltech/routify'
          </script>
          
          {#each $layout.children as node}
            <a href="{node.path}">{node.title}</a>
          {/each}

          # $leftover

            $leftover is the part of the URL that's unconsumed by Routify. Useful in wigets redirect. Often handled in _fallback.svelte.

            <!-- http://myapp.com/docs/de/i18n/intro --> <!-- src/pages/docs/_fallback.svelte --> <script> import { leftover, goto } from '@sveltech/routify' /** $leftover would be "de/i18n/intro" **/ const [language, ...fragments] = $leftover.split('/') /** After popping the language from the url we, piece it back together **/ const path = fragments.join('/') /** $redirect to "en/i18n/intro" **/ $goto(`/docs/en/${path}`) </script>
            <!-- http://myapp.com/docs/de/i18n/intro -->
            <!-- src/pages/docs/_fallback.svelte -->
            <script>
              import { leftover, goto } from '@sveltech/routify'
            
              /** $leftover would be "de/i18n/intro" **/
              const [language, ...fragments] = $leftover.split('/')
            
              /** After popping the language from the url we, piece it back together **/
              const path = fragments.join('/')
            
              /** $redirect to "en/i18n/intro" **/
              $goto(`/docs/en/${path}`)
            </script>
            Redirecting to the English page if the German page couldn't be found
            $leftover is composed by subtracting the parent folder of the _fallback.svelte from the current URL.

            # $beforeUrlChange (callback)

            • callback
              type: {Function(event):boolean}
              Function to be called before URL is changed.

            $beforeUrlChange intercepts navigation in your app. If the provided callback returns false navigation is stopped.

            <script> import { beforeUrlChange } from "@sveltech/routify" $beforeUrlChange((event, store) => { if(formIsDirty){ alert('Please save your changes before leaving.') return false } else return true }) </script>
            <script>
            import { beforeUrlChange } from "@sveltech/routify"
            $beforeUrlChange((event, store) => {
              if(formIsDirty){
                alert('Please save your changes before leaving.')
                return false
              }
              else return true
            })
            </script>

            # $afterPageLoad (callback)

            • callback
              type: {Function(page):void}
              Function to be called before URL is changed.

            Called after a page has been loaded

            <script> import { afterPageLoad } from "@sveltech/routify" $afterPageLoad(page => { console.log('loaded ' + page.title) }) </script>
            <script>
            import { afterPageLoad } from "@sveltech/routify"
            $afterPageLoad(page => {
              console.log('loaded ' + page.title)
            })
            </script>

            # $isChangingPage 1.8 beta

              Returns true if a page is loading.

              <!-- src/pages/_layout.svelte --> <script> import { isChangingPage } from '@sveltech/routify' import Spinner from '_spinner.svelte' </script> <slot /> {#if $isChangingPage} <Spinner /> {/if}
              <!-- src/pages/_layout.svelte -->
              <script>
                import { isChangingPage } from '@sveltech/routify'
                import Spinner from '_spinner.svelte'
              </script>
              
              <slot />
              
              {#if $isChangingPage}
                <Spinner />
              {/if}

              # prefetch (path, options) 1.8 betawip

              • path
                type: {String | HTMLElement}
                Path to preload. If HTMLElement is used, href attribute is used.
              • options
                type: {PrefetchObject}
                Parsed by the url helper.

              PrefetchObject
              • validFor number Seconds the response is considered fresh and preferred over a new request
              • timeout number Miliseconds to leave a hanging prefetch
              • gracePeriod number Miliseconds to wait before closing a succesful prefetch. This time allows async resources like images to load

              Prefetch pages and cache their external requests.

              <script> import { prefetch } from '@sveltech/routify' prefetch('/some/path') </script>
              <script>
                import { prefetch } from '@sveltech/routify'
                prefetch('/some/path')
              </script>
              Prefetching with Javascript

              <a href="/some/path" use:prefetch >go</a>
              <a href="/some/path" use:prefetch >go</a>
              Prefetching a link
              For redirects, use the alias $redirect . This will omit the redirecting page from browser history.

              # $focus (element)

              • element
                type: {HTMLElement}
                Focuses the element

              Focuses an element. If multiple focuses are called at once, the one closest to the root takes precedence.

              <script> import { focus } from '@sveltech/routify' </script> <h1 use:focus>Look at me</h1>
              <script>
                import { focus } from '@sveltech/routify'
              </script>
              
              <h1 use:focus>Look at me</h1>

              # $ready ()

                Call $ready() to let Routify know that your app is ready to be rendered. This is mainly used for server side rendering (SSR) where you want the server to wait for async data. If $ready is not present in your component, it will be rendered synchronously (instantly).

                Promise example
                <script> import { ready } from '@sveltech/routify' let data = {}; fetch("https://jsonplaceholder.typicode.com/todos/1") .then(response => response.json()) .then(json => {data = json}) .then($ready) </script> <h1>{data.id} - {data.title}</h1>
                <script>
                  import { ready } from '@sveltech/routify'
                    let data = {};
                
                    fetch("https://jsonplaceholder.typicode.com/todos/1")
                      .then(response => response.json())
                      .then(json => {data = json})
                      .then($ready)
                  </script>
                
                  <h1>{data.id} - {data.title}</h1>

                Await example
                <script> import { ready } from '@sveltech/routify' let data = {}; getData() async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos/1'); data = await res.json() $ready() } </script> <h1>{data.id} - {data.title}</h1>
                <script>
                  import { ready } from '@sveltech/routify'
                  let data = {};
                  getData()
                
                  async function getData() {
                    const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
                    data = await res.json()
                    $ready()
                  }
                
                </script>
                
                <h1>{data.id} - {data.title}</h1>
                If $ready is present in your code, but never called, your app will never be considered loaded. This could cause issues like hanging SSR.

                # getConcestor (path1, path2)

                • path1
                  type: {Layout | Page}
                  First Page/Layout
                • path2
                  type: {Layout | Page}
                  Second Page/Layout.

                Takes two components and returns their closest shared layout and their sibling ancestors.

                <script> import { route, getConcestor } from '@sveltech/routify' $: lastRoute = $route.last $: ([concestor, ancestor, oldAncestor] = getConcestor($route, lastRoute)) $: direction = ancestor.meta.$index - oldAncestor.meta.$index </script>
                <script>
                  import { route, getConcestor } from '@sveltech/routify'
                  $: lastRoute = $route.last
                  $: ([concestor, ancestor, oldAncestor] = getConcestor($route, lastRoute))
                  $: direction = ancestor.meta.$index - oldAncestor.meta.$index
                </script>
                getConcestor is used by getDirection to determine the direction when navigating.

                # getDirection (path1, path2)

                • path1
                  type: {Layout | Page}
                  First Page/Layout
                • path2
                  type: {Layout | Page}
                  Second Page/Layout.

                Takes two components and returns the difference between their siblings ancestors meta.$index.

                <script> import { route, getDirection } from '@sveltech/routify' $: lastRoute = $route.last $: direction = getDirection($route, lastRoute) </script>
                <script>
                  import { route, getDirection } from '@sveltech/routify'
                  $: lastRoute = $route.last
                  $: direction = getDirection($route, lastRoute)
                </script>

                Writing good documentation that is up-to-date is difficult. If you notice a mistake, help us out.