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).

<!-- src/pages/recipes/cakes/cupcakes.svelte --> <script> import { url } from '@sveltech/routify' </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'
</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.

Use $goto to navigate programatically.

<!-- src/pages/redirect.svelte --> <script> import { goto } from '@sveltech/routify' $goto('../redirect/me') </script>
<!-- src/pages/redirect.svelte -->
<script>
  import { goto } from '@sveltech/routify'
  $goto('../redirect/me')
</script>

# $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>

    # $context

      Use $context to access the current component context.

      <!-- /blog/[postId]/view.svelte --> <script> import { context } from '@sveltech/routify' console.log($context.component.name) /** /blog/:postId/view **/ </script>
      <!-- /blog/[postId]/view.svelte -->
      <script>
        import { context } from '@sveltech/routify'
        console.log($context.component.name) /** /blog/:postId/view **/
      </script>

      Components are undocumented and could change without notice. Use at own risk.


      # $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} (default value: undefined )
          • 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>

        # $focus (element)

        • element
          • type: {HTMLElement} (default value: undefined )
          • 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} (default value: undefined )
            • First Page/Layout
          • path2
            • type: {Layout | Page} (default value: undefined )
            • 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} (default value: undefined )
            • First Page/Layout
          • path2
            • type: {Layout | Page} (default value: undefined )
            • 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.