Skip to content
Christian Knuth edited this page Dec 12, 2015 · 1 revision

Welcome to the Sugar Assets wiki!

Additional Filter ideas

charset encode filter

If your have to deal with old JS files, which are not in the common UTF-8 charset format, you could convert them on the fly, so they get properly merged and minified with other JS files. Therefore you can add a custom encode filter, which could look like this:

$assets = \Assets::instance();
$assets->filter('encode',function($collection){
	/** @var \Base $f3 */
	$f3 = \Base::instance();
	$public_path = $f3->get('ASSETS.public_path');
	foreach($collection as &$asset) {
		$path = $asset['path'];
		if ($asset['type']=='js' && $asset['origin']=='internal' && isset($asset['charset']) &&
			$asset['charset'] != $f3->get('ENCODING') && is_file($path) ) {
			$path_parts = pathinfo($path);
			$filename = $path_parts['filename'].'.'.$f3->get('ENCODING').'.'.$asset['type'];
			if (!is_file($public_path.$filename) ||
				(filemtime($path)>filemtime($public_path.$filename))) {
				$data = $f3->read($path);
				if (extension_loaded('iconv'))
					$out = @iconv($asset['charset'], $f3->get('ENCODING')."//IGNORE", $data);
				if (!isset($out) || !$out)
					$out = extension_loaded('mbstring')
						? mb_convert_encoding($data,$f3->get('ENCODING'),$asset['charset'])
						: (strtoupper($asset['charset'])=='ISO-8859-1'&&
							$f3->get('ENCODING')=='UTF-8' ? utf8_encode($data) : $data);
				$f3->write($public_path.$filename,$out ?: $data);
			}
			$asset['path'] = $public_path.$filename;
		}
		unset($asset);
	}
	return $collection;
});

Now you just add it to your config: ASSETS.filter.js = encode,minify,combine and add the appropriate attribute to your js files: <F3:asset src="js/main.js" charset="ISO-8859-1" />. The main.js file now becomes converted to UTF-8 on the fly.

Clone this wiki locally