Symfony2 强制 twig 输出 XML 格式的数据 [英] Symfony2 force twig to output XML formated data
问题描述
我正在使用 Symfony2 并努力使用 twig 以 XML 格式输出数据.相反,twig 只是将大量文本块扔到浏览器上,只有当右键单击查看源代码时,我才能看到布局良好的 XML.
I am using Symfony2 and struggling to use twig to output data in a XML format. Instead what happens twig just throws massive block of text on to the browser it is only when right click to view source i can see nicely laid out XML.
有什么办法可以强制 Twig 实际输出格式化的 XML 而不是文本块,而不必查看页面源...?
Is there any way I can force Twig to actually output formatted XML instead blok of text without having to view page source...?
sitemap.xml.twig:
sitemap.xml.twig:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
{% for entry in sitemapresp %}
<loc>{{ entry['url'] }}</loc>
<lastmod>{{ entry['date'] }}</lastmod>
<changefreq>{{ entry['frequency'] }}</changefreq>
<priority>{{ entry['priority'] }}</priority>
{% endfor %}
</url>
</urlset>
浏览器输出:
http://www.sitemappro.com/2015-01-27T23:55:42+01:00daily0.5http://www.sitemappro.com/download.html2015-01-26T17:24:27+01:00daily0.5
源视图输出:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.90">
<url>
<loc>http://www.sitemappro.com/</loc>
<lastmod>2015-01-27T23:55:42+01:00</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>http://www.sitemappro.com/download.html</loc>
<lastmod>2015-01-26T17:24:27+01:00</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
</urlset>
有什么建议...?
推荐答案
如果需要页面为 XML,则需要设置响应的内容类型.
If you need the page to be XML, you will need to set the content type of the response.
$response = new Response($this->render('sitemap.xml.twig'));
$response->headers->set('Content-Type', 'application/xml; charset=utf-8');
return $response;
如果您只希望页面的一部分在 HTML 页面中呈现代码,请使用:
If you only want part of the page to render the code in an HTML page, use:
{% autoescape %}
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
{% for entry in sitemapresp %}
<loc>{{ entry['url'] }}</loc>
<lastmod>{{ entry['date'] }}</lastmod>
<changefreq>{{ entry['frequency'] }}</changefreq>
<priority>{{ entry['priority'] }}</priority>
{% endfor %}
</url>
</urlset>
{% endautoescape %}
这篇关于Symfony2 强制 twig 输出 XML 格式的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!