4

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

3
  • Seems to be Symfony 4 right? Commented Nov 1, 2018 at 18:49
  • main.css should be under public dir i guess Commented Nov 1, 2018 at 20:10
  • That is not correct path to css, double click on a CSS you want to use, click Properties and go to File Location, copy path and copy to: <link type=“text/css” rel=“stylesheet” href=“HERE”> Commented Nov 2, 2018 at 2:20

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.