load css stylesheet in twig

Viewed 1327

I'm trying to load a css file depending on who's connected. So I've concateneted my url path with the variable, I don't seem to et any erros but the css doesnt show. If you've got any advice.

cheers

My code:

<head>
        <meta charset="UTF-8" />
        <title>{% block title %}{% endblock %}-S...</title>
        {% block stylesheets %}
            {% stylesheets
                "@xxxMainBundle/Resources/css/general/*"
            %}

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">

            <!--link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous"-->
            {% if (app.session.get('courtierStyle') is defined) and (app.session.get('courtierStyle') is not null) %}
                {% set varStyle = "Sygedel/MainBundle/Resources/css/courtier/"~ app.session.get('courtierStyle') %} /*I set the var here*/

                    <link rel="stylesheet" type="text/css" href="{{ varStyle }}"/> /* and pass it in th elink tag here"

            {% endif %}
        {% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
    </head>
2 Answers

As above you need to check if the variable has the correct value and execute assets:install to copy the assets in your bundle to web/bundlename directory(where symfony load the assets) .After that you only have two options.

Option #1(the variable is a full asset reference)

like /mypath/web/favicon.ico

in this case you need to use the variable like you are doing

...
    <link rel="stylesheet" type="text/css" href="{{ varStyle }}"/> 
...

Option #2 is a reference from web folder

like favicon.ico # when you use asset('favicon.ico') the result is the option #1

in this case you need to use the variable like this:

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

after those changes you code should look like this

{% set varStyle = "bundlename"~ app.session.get('courtierStyle') %} /*I set the var here*/
<link rel="stylesheet" type="text/css" href="{{ asset('varStyle ')}}"/>

Hope it helps

You can locate your css file in to YourBundle/Resources/public/... and run app/console assets:install and access your css via path /bundle_name/... But are you sure that you need to load different css files depending on who's connected? Maybe you need render the different templates instead?

Related