2013-06-05 26 views
0

在我的Symfony項目中,我嘗試使用Chartjs.org的javascript。Uncaught ReferenceError:圖表未定義或如何在Twig中包含javascript

我把那個chart.js文件放在所有其他javascript文件所在的位置,並且在javascript.html中包含了文件以便在整個項目中可用。

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

在我的樹枝模板我嘗試實例圖所示:

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

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

這將引發一個錯誤:未捕獲的ReferenceError:圖表沒有定義

我缺少什麼?

答案:

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

更多細節:http://symfony.com/doc/2.1/cookbook/assetic/asset_management.html

+0

你確定該文件正在被加載?它是否包含在您嘗試使用它之前? – epascarello

+0

當您在Firefox或Chrome中按F12鍵時,您可以看到哪些文件加載​​失敗(開發工具)。也許該文件已加載,但在定義圖表的腳本已加載之前調用新Chart。 – HMR

+0

@HMR我剛發現文件實際上沒有加載。那麼,在Symfony2中,你將如何在整個項目中使腳本可用? –

回答

1

至於問題在哪裏把你的腳本,也許這將工作:

<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 (e.g. http://example.com), then the rendered paths should be /images/logo.png. But if your application lives in a subdirectory (e.g. http://example.com/my_app), each asset path should render with the subdirectory (e.g. /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.

+0

+1讓我走上正軌。 –

相關問題