8

I use a pre-processor to generate my CSS. I would like to include the resulting file inline, rather than as a link. Is there a way of doing this via the twig tags in Craft?

I know I could move the CSS file to the templates folder, so that I could use the include function, but is that the only and/or preferred method of achieving what I want to do? Or am I just best moving the inlining into my pre-processing? Thanks!

frontendbeast
  • 181
  • 1
  • 1
  • 4

2 Answers2

11

To simple insert raw CSS into a template from a file, you'll want to use Twig's source function. So:

<style>{{ source('file.css') }}</style>

For that file to be located somewhere outside of the templates folder, you'll have two options.

  1. Create a symlink to the file or its folder in the templates folder. Twig will be none the wiser.
  2. Add a Path to the existing template loader in Craft. This will require a custom plugin, and some digging to see how the loader is referenced in Craft. But in the end, your command will look something like this:

    $loader->addPath('path/to/other/files');

The really cool part is that paths can have namespaces in Twig. You can do this:

$loader->addPath('path/to/public', 'public');

And that let's you do this in your templates:

{{ source('@public/css/site.css') }}
Bryan Redeagle
  • 4,065
  • 13
  • 27
  • This requires the CSS files to be kept in the template folder, is that the best place to put them as they're not templates. – frontendbeast Nov 10 '15 at 10:54
  • Well, Twig's File Loader rejects paths with .., but you could get around that with a symbolic link, a custom Loader, or by adding a path to the template Loader. The second two requires a plugin. – Bryan Redeagle Nov 10 '15 at 12:35
  • 1
    I updated the question to include more info on getting files to show up in templates. – Bryan Redeagle Nov 10 '15 at 13:12
5

An alternative to the source function is using my Inlin plugin. It lets you inline files from wherever you want; the document root is the base folder, but .. works just fine.

André Elvan
  • 7,288
  • 22
  • 34