Snippet · Mecha CMS

Code snippet collection for developers.

Asset Block

Author: Taufik Nurrohman · 468 Views

Tweet

Maintainable asset URL in page content.

Using blocks in place of the base URL will make the asset URL in your page content becomes maintainable. So that, if another day you want to migrate the asset files to a different domain, you can just replace this block value instead of editing the whole pages to update the old asset URL.

// Set a block parser with ID `asset`
Block::set('asset', function($content) {
    // Replace `[‌[‌asset‌]‌]` with public asset URL
    return Block::replace('asset', To::url(ASSET), $content);
});

Usage:

---
title: Page Title
description: Page description.
author: Taufik Nurrohman
type: HTML
...

<img alt="" src="[‌[‌asset‌]‌]/png/image.png" width="50" height="50">

Tip: You can also use this method to easily switch between offline and online site. In some cases, you may want to keep the asset files structured as they should in your local environment, but also want to use a CDN service for your online assets:

Block::set('asset', function($content) use($url) {
    if ($url->host === 'localhost') {
        $base = To::url(ASSET);
    } else {
        $base = 'https://cdn.mecha-cms.com/asset';
    }
    return Block::replace('asset', $base, $content);
});

0 Comments

No comments yet.