简体   繁体   中英

Uncaught ReferenceError: Chart is not defined OR how to include javascript in Twig

In my Symfony project I try to make use of Chartjs.org's javascript.

I put the chart.js file right there where all other javascript files are located and in javascript.html I include the file so that it is available across the project.

<script src="assets/js/chart.js"></script>

In my twig template I try to instantiate Chart like this:

<canvas id="myChart" width="400" height="400"></canvas>

<script>
    var ctx = document.getElementById("myChart").getContext("2d");
    var myNewChart = new Chart(ctx);
</script>

This throws an error: Uncaught ReferenceError: Chart is not defined

What am I missing?

The answer:

{% javascripts '@AcmeFooBundle/Resources/public/js/*' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

More details: http://symfony.com/doc/2.1/cookbook/assetic/asset_management.html

As to the question where to put your scripts, maybe this will work:

<script src="{{ asset('js/propuestas_public.js') }}" type="text/javascript"></script>

http://symfony.com/doc/2.0/book/templating.html#linking-to-assets

The asset function's main purpose is to make your application more portable. If your application lives at the root of your host (eg http://example.com ), then the rendered paths should be /images/logo.png. But if your application lives in a subdirectory (eg http://example.com/my_app ), each asset path should render with the subdirectory (eg /my_app/images/logo.png). The asset function takes care of this by determining how your application is being used and generating the correct paths accordingly.

Additionally, if you use the asset function, Symfony can automatically append a query string to your asset, in order to guarantee that updated static assets won't be cached when deployed. For example, /images/logo.png might look like /images/logo.png?v2. For more information, see the assets_version configuration option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM