View.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\response;
  12. use think\Container;
  13. use think\Response;
  14. class View extends Response
  15. {
  16. // 输出参数
  17. protected $options = [];
  18. protected $vars = [];
  19. protected $filter;
  20. protected $contentType = 'text/html';
  21. /**
  22. * 处理数据
  23. * @access protected
  24. * @param mixed $data 要处理的数据
  25. * @return mixed
  26. */
  27. protected function output($data)
  28. {
  29. // 渲染模板输出
  30. $config = Container::get('config');
  31. return Container::get('view')
  32. ->init($config->pull('template'))
  33. ->filter($this->filter)
  34. ->fetch($data, $this->vars);
  35. }
  36. /**
  37. * 获取视图变量
  38. * @access public
  39. * @param string $name 模板变量
  40. * @return mixed
  41. */
  42. public function getVars($name = null)
  43. {
  44. if (is_null($name)) {
  45. return $this->vars;
  46. } else {
  47. return isset($this->vars[$name]) ? $this->vars[$name] : null;
  48. }
  49. }
  50. /**
  51. * 模板变量赋值
  52. * @access public
  53. * @param mixed $name 变量名
  54. * @param mixed $value 变量值
  55. * @return $this
  56. */
  57. public function assign($name, $value = '')
  58. {
  59. if (is_array($name)) {
  60. $this->vars = array_merge($this->vars, $name);
  61. return $this;
  62. } else {
  63. $this->vars[$name] = $value;
  64. }
  65. return $this;
  66. }
  67. /**
  68. * 视图内容过滤
  69. * @access public
  70. * @param callable $filter
  71. * @return $this
  72. */
  73. public function filter($filter)
  74. {
  75. $this->filter = $filter;
  76. return $this;
  77. }
  78. /**
  79. * 检查模板是否存在
  80. * @access private
  81. * @param string|array $name 参数名
  82. * @return bool
  83. */
  84. public function exists($name)
  85. {
  86. return Container::get('view')
  87. ->init(Container::get('config')->pull('template'))
  88. ->exists($name);
  89. }
  90. }