我正在使用Symfony2,并且正在努力使用twig以XML格式输出数据。相反,发生的事情 twig 只是将大量文本块扔到浏览器上,只有当右键单击查看源代码时,我才能看到布局精美的 XML。
有什么方法可以强制 Twig 实际输出格式化的 XML 而不是大块文本而无需查看页面源代码......?
网站地图.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,则需要设置响应的内容类型。
$response = new Response($this->render('sitemap.xml.twig'));
$response->headers->set('Content-Type', 'application/xml; charset=utf-8');
return $response;
如果只希望页面的一部分在 HTML 页面中呈现代码,请使用:
{% 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 %}
控制器端:
$response = new Response();
$response->headers->set('Content-Type', 'text/xml');
return $this->render(
'Bundle:Controller:sitemap.xml.twig',
array(
'param1' => $param1,// ...
),
$response
);
您必须仅呈现视图才能将其发送到响应。
$response = new Response($this->renderView('sitemap.xml.twig'));
$response->headers->set('Content-Type', 'application/xml; charset=utf-8');
return $response;
因此,请将$this->render(...)
替换为$this->renderView(...)
HTTP/1.0 200 OK Cache-Control: no-cache....
会消失