WordPress:将`get_template_part()` 保存到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5817726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WordPress: save `get_template_part()` to variable
提问by Atomicus
In short, all I need is to make my WordPress do this
简而言之,我所需要的就是让我的 WordPress 做到这一点
$var = get_template_part( 'loop', 'index' );
but, get_template_part()
does not return HTML, it prints it.
I need this HTML stored in $var
- do you have any ideas how to do it?
但是,get_template_part()
不返回 HTML,而是打印它。
我需要这个 HTML 存储在$var
- 你有什么想法怎么做吗?
回答by Simon Scarfe
This isn't what get_template_part
was for, get_template_part essentially behaves like PHP's require function. Justin Tadlock writes a lot more about this hereand also talks about a Wordpress function that might be more useful to you - locate_template
.
这不是get_template_part
为了什么, get_template_part 本质上就像 PHP 的 require 函数。贾斯汀·塔德洛克 (Justin Tadlock) 在这里写了很多关于这方面的文章,还谈到了一个可能对您更有用的 Wordpress 功能 - locate_template
。
Alternatively, if you did want to hack this functionality using get_template_part, you could use template buffering:
或者,如果您确实想使用 get_template_part 破解此功能,则可以使用模板缓冲:
function load_template_part($template_name, $part_name=null) {
ob_start();
get_template_part($template_name, $part_name);
$var = ob_get_contents();
ob_end_clean();
return $var;
}
回答by Tom Auger
I'm not loving Output Buffering, though +1 for even thinking of that as an option!
我不喜欢输出缓冲,尽管 +1 甚至认为这是一种选择!
I think Helga was on to something, but you need to still respect the child_themes and the theme path, so use locate_template()
instead (also as Simon suggested).
我认为 Helga 正在做一些事情,但是您仍然需要尊重 child_themes 和主题路径,因此请locate_template()
改用(也如 Simon 建议的那样)。
This works nicely, and can even be used inside a filter or (in my case) shortcode function (I wanted my shortcode to output the content within a template-style file, to separate the display layer from the logic layer).
这很好用,甚至可以在过滤器或(在我的情况下)短代码函数中使用(我希望我的短代码输出模板样式文件中的内容,以将显示层与逻辑层分开)。
return file_get_contents(locate_template("template-file-name.php")); // don't forget the .php!
回答by helgatheviking
what about?
关于什么?
$file = file_get_contents(STYLESHEETPATH . '/template-part.php');
return $file;
i'm sure there is a better way, but that seems to work for me.
我确定有更好的方法,但这似乎对我有用。