View.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\Config;
  13. use think\Response;
  14. use think\View as ViewTemplate;
  15. class View extends Response
  16. {
  17. // 输出参数
  18. protected $options = [];
  19. protected $vars = [];
  20. protected $replace = [];
  21. protected $contentType = 'text/html';
  22. /**
  23. * 处理数据
  24. * @access protected
  25. * @param mixed $data 要处理的数据
  26. * @return mixed
  27. */
  28. protected function output($data)
  29. {
  30. // 渲染模板输出
  31. return ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str'))
  32. ->fetch($data, $this->vars, $this->replace);
  33. }
  34. /**
  35. * 获取视图变量
  36. * @access public
  37. * @param string $name 模板变量
  38. * @return mixed
  39. */
  40. public function getVars($name = null)
  41. {
  42. if (is_null($name)) {
  43. return $this->vars;
  44. } else {
  45. return isset($this->vars[$name]) ? $this->vars[$name] : null;
  46. }
  47. }
  48. /**
  49. * 模板变量赋值
  50. * @access public
  51. * @param mixed $name 变量名
  52. * @param mixed $value 变量值
  53. * @return $this
  54. */
  55. public function assign($name, $value = '')
  56. {
  57. if (is_array($name)) {
  58. $this->vars = array_merge($this->vars, $name);
  59. return $this;
  60. } else {
  61. $this->vars[$name] = $value;
  62. }
  63. return $this;
  64. }
  65. /**
  66. * 视图内容替换
  67. * @access public
  68. * @param string|array $content 被替换内容(支持批量替换)
  69. * @param string $replace 替换内容
  70. * @return $this
  71. */
  72. public function replace($content, $replace = '')
  73. {
  74. if (is_array($content)) {
  75. $this->replace = array_merge($this->replace, $content);
  76. } else {
  77. $this->replace[$content] = $replace;
  78. }
  79. return $this;
  80. }
  81. }