add custom css to twig template, style not applying

Viewed 4503

I am trying really hard to somehow link my main.css to my html templates in twig. Im not sure why its not working properley, and i ran out of ideas.

I have added this line in my head block in my base html file.

<link type="text/css" rel="stylesheet" {{ source('main.css') }}">

This is all i have in my css file

body{
   background: red;
}

Here is my folder structure

enter image description here

1 Answers

enter image description here

You should create main.css in a path relative to templating directory.

The problem is source is not the thing you are probably after. look at the template below:

Twig

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link type="text/css" rel="stylesheet" {{ source('main.css') }}">
    </head>
    <body>
        This is Body
    </body>
</html>

the produced HTML source in browser is this:

HTML Source

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link type="text/css" rel="stylesheet" body{ background: red;}">
    </head>
    <body>
        This is Body
    </body>
</html>

You are probably after asset twig function:

<link type="text/css" rel="stylesheet" {{ asset('main.css') }}">

Please note that, asset gets path relative to public directory, so you should put your web assets inside public, not templating.

If you are using Symfony 4, you should also install symfony/asset:

composer require symfony/asset

You may read more on this here: Creating and Using Templates, Linking to Assets

Related