简体   繁体   English

如何在模板中获取Kohana base_url

[英]How to get Kohana base_url in template

In Kohana 3 bootstrap.php one can define base_url : Kohana 3 bootstrap.php可以定义base_url

Kohana::init(array(
    'base_url'   => '/foo/',
));

This usually means also moving the /js/ , /css/ and other media to that base dir like /foo/js/ , /foo/css/ . 这通常还意味着还将/js//css/和其他媒体移动到该基本目录,例如/foo/js//foo/css/ My question is not to discuss good or bad of such. 我的问题不是讨论这种情况的好坏。

Is there a built-in way in Kohana to access the base_url from a template (just like in Django you can use {{ MEDIA_URL }}css/ )? Kohana中是否有内置的方式可以从模板访问base_url (就像在Django中,您可以使用{{ MEDIA_URL }}css/ )?

You can output the base url as using URL::base : 您可以使用URL::base输出基本网址:

<?php echo URL::base(); ?>

If you're outputting a url relative to that you probably want URL::site : 如果要输出相对于该URL::site ,则可能需要URL::site

<?php echo URL::site('css/'); ?>

Kohana 3 template controllers use the View class to render templates. Kohana 3模板控制器使用View类来呈现模板。 Views are normal php files and have no special syntax, so just use the normal <?php ... ?> tags as above. 视图是普通的php文件,没有特殊的语法,因此请使用上述普通的<?php ... ?>标记。 The View class allows you to declare variables for use in that view, before you render it. View类允许您在渲染视图之前声明要在该视图中使用的变量。

One good way is that in your layout view, in the head of the HTML you put near the <title> tag: 一种好方法是在布局视图中的<title>标签附近放置HTML的开头:

<base href="<?php echo URL::base(TRUE) ?>">

and then, you load your assets this way: 然后,您可以通过以下方式加载资产:

<img src="assets/images/img.jpg" alt="">

The HTML <base> tag is a way of defining a base URL for all the assets in the page. HTML <base>标记是一种为页面中所有资产定义基本URL的方法。 This way you load your image located at /foo/assets/images/img.jpg without making a URL::base() call in every tag. 这样,您就可以加载位于/foo/assets/images/img.jpg的图像,而无需在每个标记中调用URL::base() I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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