Link resolving

When working with fields type such as Link or Structured Text, the prismic.io kit will need to generate links to documents within your website.

Since routing is specific to your site, you will need to define it and provide it to some of the methods used on the fields.

A link resolver is provided in every starter kit, but you may need to adapt it or write your own if you're using a different framework.

Copy
      var html = doc.getStructuredText('blog-post.body').asHtml({
  linkResolver: function (doc) {
    // Pretty URLs for known types
    if (doc.type === 'blog') return "/post/" + doc.uid;
    if (doc.type === 'page') return "/" + doc.uid;
    // Fallback for other types, in case new custom types get created
    return "/doc/" + doc.id;
  }
});
    
Copy
      <?php
use Prismic\LinkResolver;

class StarterKitLinkResolver extends LinkResolver
{
    public function resolve($link)
    {
        if($link instanceof Prismic\Fragment\Link\DocumentLink) {
            if ($link->isBroken()) {
                return;
            }
            if ($link->getType() == 'category') {
                return '/category/'.$link->getUid();
            }
            if ($link->getType() == 'post') {
                $date = $link->getDate('post.date');
                $year = $date ? $date->asDateTime()->format('Y') : '0';
                $month = $date ? $date->asDateTime()->format('m') : '0';
                $day = $date ? $date->asDateTime()->format('d') : '0';
                return '/blog/'.$year.'/'.$month.'/'.$day.'/'.urlencode($link->getUid());
            }
            // This is a generic route for user-created document masks.
            // To have nicer looking URLs, it is recommended to add a specific rule for any mask you create.
            return '/document/' . $link->getId() . '/' . $link->getSlug();
        } else {
            return $link->getUrl();
        }
    }
}