Snippets

Streamlines code input by allowing users to insert pre-defined HTML snippets with ease, enhancing efficiency in text editing.

Click the 'Add' (+) button on the toolbar to open addbar and then click on 'Snippets'.

Code

<!DOCTYPE html>
<html>
    <head>
        <title>Redactor</title>
        <meta charset="utf-8">

        <!-- css -->
        <link rel="stylesheet" href="/your-folder/redactor.css" />
    </head>
    <body>
        <!-- element -->
        <textarea id="entry">...</textarea>

        <!-- js -->
        <script src="/your-folder/redactor.js"></script>
        <script src="/your-folder/plugins/snippets/snippets.js"></script>

        <!-- call -->
        <script>
        Redactor('#entry', {
            plugins: ['snippets'],
            snippets: '/your-folder/snippets.json'
        });
        </script>
    </body>
</html>

Usage

Snippets are prepared code sections consisting of any html elements. The snippets setting allows you to get snippets from JSON file.


Redactor('#entry', {
    snippets: '/my-snippets/snippets.json'
});

Example of JSON:


{
    "mysnippet": {
        "name": "My Snippet",
        "html": "<h1>...</h1><p>...</p>"
    },
    "mysnippet2": {
        "name": "My Other Snippet",
        "html": "<h2>...</h2><div><p>...</p></div>"
    }
}

Or you can set the JSON object directly to the setting like this:


Redactor('#entry', {
    snippets: {
        "mysnippet": {
            "name": "My Snippet",
            "html": "..."
        },
        "mysnippet2": {
            "name": "My Other Snippet",
            "html": "..."
        }
    }
});

Redactor builds a preview of the snippet automatically as an html preview. But for more accurate display, you can specify a screenshot of the snippet with image size 160x80px:


{
    "mysnippet": {
        "name": "My Snippet",
        "image": "my-snippets/my-snippet.png",
        "html": "..."
    }
}

CSS

Redactor overrides content styles unless you have nostyle: true setting enabled. So a snippet can show incorrectly even if CSS snippet styles are present on your page where the editor is running. That's why it's better to add styles defining the snippet to the page, for example like this:


<style>
/* snippet styles on your page */
.mysnippet p {
    ...
}

/* snippet styles for Redactor */
.rx-content .mysnippet p {
    ...
}
</style>

See more about overriding styles.