• Stars
    star
    107
  • Rank 322,633 (Top 7 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 9 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DEPRECATED A simple plugin that allows you to minify blocks of HTML, CSS, and JS inline in Craft CMS templates

No Maintenance Intended

DEPRECATED

This Craft CMS 2.x plugin is no longer supported, but it is fully functional, and you may continue to use it as you see fit. The license also allows you to fork it and make changes as needed for legacy support reasons.

The Craft CMS 3.x version of this plugin can be found here: craft-minify and can also be installed via the Craft Plugin Store in the Craft CP.

Minify plugin for Craft CMS

A simple plugin that allows you to minify blocks of HTML, CSS, and JS inline in Craft CMS templates

Related: Minify for Craft 3.x

Installation

  1. Download & unzip the file and place the minify directory into your craft/plugins directory
  2. -OR- do a git clone https://github.com/khalwat/minify.git directly into your craft/plugins folder. You can then update it with git pull
  3. -OR- install with Composer via composer require nystudio107/minify
  4. Install plugin in the Craft Control Panel under Settings > Plugins
  5. The plugin folder should be named minify for Craft to see it. GitHub recently started appending -master (the branch name) to the name of the folder for zip file downloads.

Configuring Minify

There is nothing to configure

Using the Minify plugin in your templates

Minify adds several block tags for minifying HTML, CSS, and JS inline in your templates. Minify does not minify external CSS or JS files. Use grunt or gulp task runners to set up a workflow that minimizes these as part of your build process.

You can nest any number of the various {% minify %} tags as you wish.

Why minify inline HTML/CSS/JS code?

Twig provides the {% spaceless %} tag, but it is not intended for use as a way to properly minify HTML/CSS/JS code.

You already properly gzip output via mod_deflate with Apache or by enabling compression with Nginx for optimal delivery on production. You already use a task runner like grunt or gulp or CodeKit to minimize static resources like CSS/JS files. What's the point of minifying HTML/CSS/JS inline?

Firstly, you want to keep HTML/CSS/JS comments and a nice hierarchical structure to your code, with plenty of readable whitespace for development, but want all of this stripped out of the HTML/CSS/JS that is served to your frontend.

Secondly, not all CSS/JS can or should be in static asset files. Sometimes you need inline Javascript for efficiency reasons, or if you're using JSON-LD for Google Structured Data/SEO purposes inline in your HTML files. You may also want to be able to use the Craft templating engine in your CSS/JS itself.

Finally, if you minify any code you wrap in {% cache %} tags, that means it will be stored minified in the database, reducing db size and (marginally) transactional overhead.

Minifying Everything

You can wrap any arbitrary HTML/Twig code in the following block tags to minify it:

{% minify %}
	(HTML/Twig code here)
{% endminify %}

...and the resulting HTML output will be stripped of comments, empty space, etc.

Using the {% minify %} on its own with no parameters (see below) will minify HTML, as well as any inline CSS (in <style> tag pairs) and any inline Javascript (in <script> tag pairs).

Minifying HTML

You can wrap any arbitrary HTML/Twig code in the following block tags to minify it:

{% minify html %}
	(HTML/Twig code here)
{% endminify %}

...and the resulting HTML output will be stripped of comments, empty space, etc.

It will ignore <script> and <style> tag pairs in the minification. You should specifically wrap your inline CSS/JS in {% minify css %} and {% minify js} tag blocks if you want those minimized as well; see below.

Minifying CSS

You can wrap any arbitrary <style> CSS code in the following block tags to minify it:

{% minify css %}
	<style>
		(Inline CSS styles here)
	</style>
{% endminify %}

...and the resulting CSS output will be stripped of comments, empty space, etc.

Minifying JS

You can wrap any arbitrary <script> JS code in the following block tags to minify it:

{% minify js %}
	<script>
		(Inline JS code here)
	</script>
{% endminify %}

...and the resulting JS output will be stripped of comments, empty space, etc.

Minify all the things

If you want to minify your entire HTML on the frontend, you can simply wrap your entire _layout.twig template (the one that other templates extends):

{% minify %}
		(Entire base HTML/Twig template here)
{% endminify %}

However, understand the potential performance implications. On large HTML/CSS/JS blocks minification is not cheap, and if you do it this way, every single HTTP request will spend extra cycles minimizing your entire template.

It works fine for HTML/CSS/JS templates that aren't too huge, but measure any performance impact by profiling your website before and after wrapping the entire _layout.twig template to ensure you're not introducing additional latency in the http requests.

On most sites, the overhead that spinning up PHP and Craft takes is the majority of the TTFB (Time To First Byte), and this is not adversely affected by minifying the entire HTML as described here.

Cache as cache can

A great way to use the {% minify %} tags is to wrap them in {% cache %} tags:

{% cache %}
	{% minify %}
		(HTML/Twig code here)
	{% endminify %}
{% endcache %}

As with {% cache %} tags, you canโ€™t use {% minify %} tags outside of top-level {% block %} tags within a template that extends another. Read more about cache tags

A nice side-benefit of minifying HTML inside of {% cache %} tags is that the text that is stored in the database as a cache is minified itself.

If you've already implemented a caching system to reduce server response time, adding {% minify %} tags to the mix is a natural.

Minify craft.config settings

Minify offers two craft.config (set in your config/general.php) to allow you to control its behavior:

disableTemplateMinifying if set to true then Minify will not minify anything

disableDevmodeMinifying if set to true then Minify will not minify anything if devMode is enabled

Why does my minified HTML/CSS still have linebreaks?

Minify uses the Minify PHP library. Here's their official explanation:

Why do the CSS & HTML minifiers add so many line breaks?

TL;DR: Ignore them. They don't add to the output size and if you absolutely want all content on one line you will have to use another tool.

It's rumored that some source control tools and old browsers don't like very long lines. Compressed files with shorter lines are also easier to diff.

Since both Minify classes are regex-based, it would be very difficult/error-prone to count characters then try to re-establish context to add line breaks. Instead, both classes trade 1 space for 1 line break (\n) wherever possible, adding breaks but without adding bytes.

If you can think of another safe & efficient way to limit lines in these two tools without adding bytes, please submit a patch, but this is not something anyone should be worrying about.

Brought to you by nystudio107

More Repositories

1

annotated-webpack-config

This is the companion github repo for the "An Annotated webpack 4 Config for Frontend Web Development" article.
JavaScript
434
star
2

craft-scripts

Shell scripts to manage database backups, asset backups, file permissions, asset syncing, cache clearing, and database syncing between Craft CMS environments
Shell
364
star
3

seomatic

DEPRECATED A turnkey SEO implementation for Craft CMS 2.x that is comprehensive, powerful, and flexible
PHP
357
star
4

nginx-craft

An Nginx virtual host configuration for Craft CMS that implements a number of best-practices.
307
star
5

craft

nystudio107 Craft 3 CMS scaffolding project
Twig
289
star
6

craft-imageoptimize

Automatically create & optimize responsive image transforms, using either native Craft transforms or a service like Imgix, with zero template changes.
PHP
235
star
7

retour

DEPRECATED Retour allows you to intelligently redirect legacy URLs, so that you don't lose SEO value when rebuilding & restructuring a website.
PHP
168
star
8

craft-seomatic

SEOmatic facilitates modern SEO best practices & implementation for Craft CMS 3. It is a turnkey SEO system that is comprehensive, powerful, and flexible.
PHP
163
star
9

instantanalytics

DEPRECATED Instant Analytics brings full Google Analytics support to your Twig templates and automatic Craft Commerce integration with Google Enhanced Ecommerce.
PHP
101
star
10

craft-twigpack

Twigpack is a bridge between Twig and webpack, with manifest.json & webpack-dev-server HMR support
PHP
97
star
11

rollup-plugin-critical

Vite.js & Rollup plugin for generating critical CSS
TypeScript
88
star
12

devmode

Website for the devMode.fm podcast
Twig
85
star
13

craft-multi-environment

Efficient and flexible multi-environment config for Craft CMS
PHP
83
star
14

vitejs-docker-dev

Local development environment for developing vite.js via Docker container
Makefile
80
star
15

generator-craftplugin

generator-craftplugin is a Yeoman generator for Craft CMS plugins
PHP
73
star
16

craft3-multi-environment

DEPRECATED Efficient and flexible multi-environment config for Craft CMS
72
star
17

craft-typogrify

Typogrify prettifies your web typography by preventing ugly quotes and 'widows' and more
PHP
70
star
18

cookies

DEPRECATED Secure Cookies for Twig Templates in Craft CMS
PHP
68
star
19

generator-craftinstall

DEPRECATED generator-craftinstall is a Yeoman generator for Craft CMS installs
JavaScript
57
star
20

craft-vite

Allows the use of the Vite.js next generation frontend tooling with Craft CMS
PHP
50
star
21

buffer

DEPRECATED Send social updates to Twitter, Facebook, etc. through Buffer.com via Twig templates, URLs, and plugins.
PHP
44
star
22

richvariables

DEPRECATED Allows you to easily use Craft Globals as variables in Rich Text fields
PHP
44
star
23

craft-transcoder

Transcode video & audio files to various formats, and provide video thumbnails
PHP
43
star
24

craft-autocomplete

Provides Twig template IDE autocomplete of Craft CMS & plugin variables
PHP
41
star
25

recipe

DEPRECATED A comprehensive recipe FieldType for Craft CMS that includes metric/imperial conversion, portion calculation, and JSON-LD microdata support
PHP
38
star
26

craft-cookies

A simple plugin for setting and getting cookies from within Craft CMS templates.
PHP
37
star
27

craft-retour

Retour allows you to intelligently redirect legacy URLs, so that you don't lose SEO value when rebuilding & restructuring a website
PHP
36
star
28

craft-minify

A simple plugin that allows you to minify blocks of HTML, CSS, and JS inline in Craft CMS templates
PHP
36
star
29

twig-bundle-installer

Install, update, and manage Twig template bundles via Composer
PHP
35
star
30

dotenvy

Speed up your production sites by ditching .env for key/value variable pairs as Apache, Nginx, and shell equivalents
PHP
32
star
31

spin-up-craft

Spin up a working Craft CMS instance quickly & easily with Docker
Dockerfile
31
star
32

craft-routemap

Returns a list of Craft/Vue/React route rules and element URLs for ServiceWorkers from Craft entries
PHP
31
star
33

craft-recipe

A comprehensive recipe FieldType for Craft CMS that includes metric/imperial conversion, portion calculation, and JSON-LD microdata support
PHP
28
star
34

routemap

DEPRECATED Returns a list of Craft/Vue/React route rules and entry & asset URLs for ServiceWorkers from Craft entries
PHP
28
star
35

craft-similar

Similar for Craft lets you find elements, Entries, Categories, Commerce Products, etc, that are similar, based on... other related elements.
PHP
26
star
36

disqus

DEPRECATED Integrate the Disqus commenting system into Craft CMS websites, including Single Sign On (SSO) and custom login/logout URLs.
PHP
26
star
37

craft-emptycoalesce

Empty Coalesce adds the ??? operator to Twig that will return the first thing that is defined, not null, and not empty
PHP
26
star
38

eagerbeaver

DEPRECATED Allows you to eager load elements from auto-injected Entry elements on demand from your templates.
PHP
25
star
39

transcoder

DEPRECATED Transcode videos to various formats, and provide thumbnails of the video
PHP
25
star
40

craft-richvariables

Allows you to easily use Craft Globals as variables in Rich Text fields
PHP
25
star
41

craft-webperf

Webperf helps you build & maintain high quality websites through Real User Measurement of your website's performance
PHP
25
star
42

plugindev

nystudio107 Craft CMS plugin development environment scaffolding
PHP
23
star
43

fastcgicachebust

DEPRECATED Bust the Nginx FastCGI Cache when entries are saved or created.
PHP
22
star
44

craft-closure

Allows you to use arrow function closures in Twig
PHP
22
star
45

craft-twigprofiler

Twig Profiler allows you to profile sections of your Twig templates, and see the resulting timings in the Yii2 Debug Toolbar
PHP
21
star
46

craft-templatecomments

Adds a HTML comment with performance timings to demarcate `{% block %}`s and each Twig template that is included or extended.
PHP
20
star
47

craft-instantanalytics

Instant Analytics brings full Google Analytics support to your Twig templates and automatic Craft Commerce integration with Google Enhanced Ecommerce.
PHP
20
star
48

pathtools

DEPRECATED This twig plugin for the Craft CMS brings convenient path & url manipulation functions & filters to your Twig templates.
PHP
20
star
49

craft-fastcgicachebust

Bust the Nginx FastCGI Cache when entries are saved or created.
PHP
20
star
50

spin-up-statamic

Spin up a working Statamic instance quickly & easily with Docker
PHP
18
star
51

site-module

An example module for Craft CMS 3 that lets you enhance your websites with a custom site module
PHP
18
star
52

save-remote-file-webpack-plugin

webpack 4 plugin to download remote files, and save them locally
JavaScript
17
star
53

craft-youtubeliveembed

This plugin allows you to embed a YouTube live stream and/or live chat on your webpage
PHP
17
star
54

craft-connect

Allows you to connect to external databases and perform db queries
PHP
16
star
55

craft-twigfield

DEPRECATED: Provides a twig editor field with Twig & Craft API autocomplete
PHP
15
star
56

craft-eagerbeaver

DEPRECATED: Allows you to eager load elements from auto-injected Entry elements on demand from your templates.
PHP
14
star
57

tailwind-css-performance

Small repo to demonstrate the slow building of Tailwind CSS using `webpack-dev-server` HMR & PostCSS
JavaScript
13
star
58

docker-images

Docker image source files
Dockerfile
13
star
59

disclosedassets

DEPRECATED Allow your clients to find asset sub-folders by disclosing them by default
PHP
13
star
60

craft-disqus

Integrates the Disqus commenting system into Craft 3 websites, including Single Sign On (SSO) and custom login/logout URLs
PHP
12
star
61

vanillaforums

DEPRECATED Single Sign On plugin for VanillaForums/jsConnect and CraftCMS
PHP
11
star
62

craft-pathtools

This twig plugin for the Craft CMS brings convenient path & url manipulation functions & filters to your Twig templates.
PHP
11
star
63

craft-plugin-vite

Plugin Vite is the conduit between Craft CMS plugins and Vite, with manifest.json & HMR support
PHP
10
star
64

craft-units

Units is a plugin that can convert between any units of measure, and comes with a Field for content authors to use
PHP
9
star
65

craft-icalendar

Tools for parsing & formatting the RFC 2445 iCalendar (.ics) specification
PHP
8
star
66

gatsby-concurrent-mode

Enable Concurrent Mode in in React for Gatsby projects.
JavaScript
8
star
67

charcuterie-vue-vitest

charcuterie-vue-vitest
TypeScript
6
star
68

get-webpack-config

Utilities to help you modularize your webpack configs
JavaScript
6
star
69

craft-plugin-vite-buildchain

A drop-in buildchain for using Vite in your Craft CMS plugins or modules
TypeScript
6
star
70

create-symlink-webpack-plugin

webpack 4 plugin to generate symlinks
JavaScript
5
star
71

spin-up-statamic-starter

Starter kit to add Spin Up Statamic to your existing Statamic project
PHP
4
star
72

craft-code-field

Provides a Code Field that has a full-featured code editor with syntax highlighting & autocomplete
PHP
4
star
73

craft-code-editor

Provides a code editor field with Twig & Craft API autocomplete
PHP
4
star
74

craft-plugin-manifest

Plugin Manifest is the conduit between Craft CMS plugins and webpack, with manifest.json & webpack-dev-server HMR support
PHP
4
star
75

matrixfacades

This is a project demonstrates how to improve authoring experience Matrix Faรงades
PHP
4
star
76

.github

3
star
77

craft-vanillaforums

Single Sign On plugin for Vanilla Forums/jsConnect and CraftCMS
PHP
3
star
78

vitepress-starter

Starter repository for VitePress documenation
3
star
79

craft-twig-sandbox

Allows you to easily create a sandboxed Twig environment where you can control what tags, filters, functions, and object methods/properties are allowed
PHP
3
star
80

craft-twig-base-templates

Craft CMS Twig base templates
Twig
3
star
81

craft-instantanalytics-ga4

Instant Analytics brings full Google GA4 server-side analytics support to your Twig templates and automatic Craft Commerce integration
PHP
3
star
82

craft-imageoptimize-thumbor

Provides an Thumbor image transform type for the ImageOptimize plugin
PHP
2
star
83

craft-imageoptimize-imgix

Provides an Imgix image transform type for the ImageOptimize plugin.
PHP
2
star
84

docker-yeoman

node yeoman Docker images
Dockerfile
2
star
85

craft-imageoptimize-sharp

Provides an Sharp image transform type for the ImageOptimize plugin
PHP
2
star
86

fwt

Website for the Friends of Webster Trails website http://webstertrails.org/
Twig
2
star
87

test-twig-bundle

Test bundle of Twig templates for Bundle Installer
Twig
2
star
88

schemagen

Generates PHP models representing schema.org JSON-LD types
PHP
2
star
89

entitydecode

DEPRECATED Decodes HTML Entities
PHP
1
star
90

spin-up-statamic-peak

Spin up a working Statamic Peak quickly & easily with Docker
PHP
1
star
91

srcsetdev

TypeScript
1
star
92

craft-twig-base-components

Craft CMS Twig base components
Twig
1
star