php学习笔记(四十一)smarty3的一些新特性

smarty运算符 php5会使用的smarty运算符,smarty是在php前期使用中常见的模版分离,同时国内鼎鼎大名的ecshop也是采用这样方式开发系统 立即下载

BETA8 需要注意的事情
Smarty3 的API已经被重构过以更好的面向结构话和语法一致性。但是Smarty2的API仍然是支持的,但是会出提示。

当然,也可以手动disable掉这个提示,但是强烈推荐你将你的语法升级到适应Smarty3的语法

Smarty3中所有的方法命名都采用”fooBarBaz”的方式,而且,所有的Smarty属性都含有getters和setters,举例:

老版本中设置Cache的路径

$smarty->cache_dir
现在可以这样作:

$smarty->setCacheDir('foo/')
并且可以通过如下方法获取:

$smarty->getCacheDir()
一些smarty3的api比如以isXX开头的方法已经被取消,因为现在已经有实现相同功能的类似getXX的方法代替了

以下是一个简单的API列表

$smarty->fetch($template, $cache_id = null, $compile_id = null, $parent = null)
$smarty->display($template, $cache_id = null, $compile_id = null, $parent = null)
$smarty->isCached($template, $cache_id = null, $compile_id = null)
$smarty->createData($parent = null)
$smarty->createTemplate($template, $cache_id = null, $compile_id = null, $parent = null)
$smarty->enableSecurity()
$smarty->disableSecurity()
$smarty->setTemplateDir($template_dir)
$smarty->addTemplateDir($template_dir)
$smarty->templateExists($resource_name)
$smarty->loadPlugin($plugin_name, $check = true)
$smarty->loadFilter($type, $name)
$smarty->setExceptionHandler($handler)
$smarty->addPluginsDir($plugins_dir)
$smarty->getGlobal($varname = null)
$smarty->getRegisteredObject($name)
$smarty->getDebugTemplate()
$smarty->setDebugTemplate($tpl_name)
$smarty->assign($tpl_var, $value = null, $nocache = false, $scope = SMARTY_LOCAL_SCOPE)
$smarty->assignGlobal($varname, $value = null, $nocache = false)
$smarty->assignByRef($tpl_var, &$value, $nocache = false, $scope = SMARTY_LOCAL_SCOPE)
$smarty->append($tpl_var, $value = null, $merge = false, $nocache = false, $scope = SMARTY_LOCAL_SCOPE)
$smarty->appendByRef($tpl_var, &$value, $merge = false)
$smarty->clearAssign($tpl_var)
$smarty->clearAllAssign()
$smarty->configLoad($config_file, $sections = null)
$smarty->getVariable($variable, $_ptr = null, $search_parents = true, $error_enable = true)
$smarty->getConfigVariable($variable)
$smarty->getStreamVariable($variable)
$smarty->getConfigVars($varname = null)
$smarty->clearConfig($varname = null)
$smarty->getTemplateVars($varname = null, $_ptr = null, $search_parents = true)
一些API的调用是通过它自己的对象完成的

$smarty->cache->loadResource($type = null)
$smarty->cache->clearAll($exp_time = null, $type = null)
$smarty->cache->clear($template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null)

$smarty->register->block($block_tag, $block_impl, $cacheable = true, $cache_attr = array())
$smarty->register->compilerFunction($compiler_tag, $compiler_impl, $cacheable = true)
$smarty->register->templateFunction($function_tag, $function_impl, $cacheable = true, $cache_attr = array())
$smarty->register->modifier($modifier_name, $modifier_impl)
$smarty->register->templateObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array())
$smarty->register->outputFilter($function_name)
$smarty->register->postFilter($function_name)
$smarty->register->preFilter($function_name)
$smarty->register->resource($resource_type, $function_names)
$smarty->register->variableFilter($function_name)
$smarty->register->defaultPluginHandler($function_name)
$smarty->register->defaultTemplateHandler($function_name)

$smarty->unregister->block($block_tag)
$smarty->unregister->compilerFunction($compiler_tag)
$smarty->unregister->templateFunction($function_tag)
$smarty->unregister->modifier($modifier)
$smarty->unregister->templateObject($object_name)
$smarty->unregister->outputFilter($function_name)
$smarty->unregister->postFilter($function_name)
$smarty->unregister->preFilter($function_name)
$smarty->unregister->resource($resource_type)
$smarty->unregister->variableFilter($function_name)

$smarty->utility->compileAllTemplates($extention = '.tpl', $force_compile = false, $time_limit = 0, $max_errors = null)
$smarty->utility->clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null)
$smarty->utility->testInstall()
然后是所有的getters和setters,可以用来获取和设置所有属性,以下是一些例子:

$caching = $smarty->getCaching();      // get $smarty->caching
$smarty->setCaching(true);             // set $smarty->caching
$smarty->setDeprecationNotices(false); // set $smarty->deprecation_notices
$smarty->setCacheId($id);              // set $smarty->cache_id
$debugging = $smarty->getDebugging();  // get $smarty->debuggin
目录结构
和Smarty2结构类似

index.php
/libs/
    Smarty.class.php   #主文件
/libs/sysplugins/  #内部plugin
    internal.
/plugins/   #外部plugin,可自由扩充
    function.mailto.php
    modifier.escape.php2
/templates/   #模板,可以是纯php或传统的smarty模板
    index.tpl
    index_view.php
非常多的Smarty3核心功能函数是放在sysplugins目录底下,你不需要去修改其中的任何文件

它的插件文件则是放在/lib/plugins目录底下,你可以在其中增加你自己的插件文件。

你仍然需要创建自己的cache/,templates/, template_c/, configs/目录,并且要保证cache/,template_c两个目录具有写权限

简单调用
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('foo','bar');
$smarty->display('index.tpl');)))
区别
虽然Smarty3在模板使用起来和以前没有区别,但是其实内部逻辑是截然不同的,却也是能够和2进行兼容

除了以下几点

1.Smarty3只能运行在PHP5环境下,不再支持PHP4
2.{php}标签默认是关闭的,可以通过如下方式打开 
$smarty->allow_php_tag=true

3.模板标签将不支持空格,如{ $abc }在Smarty2中可以识别的,但是3里头就不行了,必须这样{$abc},这样是为了能够更好的支持javascript和css,但是你仍然可以通过设置来支持原来的形式 
$smarty->auto_literal = false;

4.Smarty3的API有一定的不同,但是仍然支持Smarty2
词法特性
Smarty3 采用一个词法分析器来进行模板的解析和编译,基于这种方式,它可以支持一些语法扩展来让生活变得更加美好!

比如模板内部的数学计算,直观,简短的函数参数选项,以及无穷的函数递归,更准确的错误处理等等

新的功能
表达式
支持更加随意的表达式

{$x+$y}                           输入x和y的和
{$foo = strlen($bar)}             变量支持PHP函数
{assign var=foo value= $x+$y}     属性支持表达式
{$foo = myfunct( ($x+$y)*3 )}     函数参数支持表达式
{$foo[$x+3]}                      数组下表支持表达式
引号中可以使用变量

{$foo="this is message {counter}"}
可以在模板里头定义数组

{assign var=foo value=[1,2,3]}
{assign var=foo value=['y'=>'yellow','b'=>'blue']}
{assign var=foo value=[1,[9,8],3]}
简单的变量赋值

{$foo=$bar+2}
可以给指定的数组元素赋值,如果变量存在但不是数组,会先转换成数组,再进行赋值

{$foo['bar']=1}
{$foo['bar']['blar']=1}
同上,可以给数组添加值

{$foo[]=1}
对象的属性支持”.”操作符

{$foo.a.b.c}        =>  $foo['a']['b']['c']
{$foo.a.$b.c}       =>  $foo['a'][$b]['c']
{$foo.a.{$b+4}.c}   =>  $foo['a'][$b+4]['c']
{$foo.a.{$b.c}}     =>  $foo['a'][$b['c']]
变量名中支持变量

$foo         一个普通的变量
$foo_{$bar}  变量名中包含变量
$foo_{$x+$y} 变量名中可以支持表达式
$foo_{$bar}_buh_{$blar}  变量名包含多个变量
{$foo_{$x}}  如果$x是1,则输出$foo_1
支持对象链,即是对象方法的连续调用,很像jquery

{$object->method1($x)->method2($y)}
{for}标签支持类似loop一样的循环

{for $x=0, $y=count($foo); $x<$y; $x++}  ....  {/for}
在FOR循环中可以通过如下特殊标示符限定位置:

$x@iteration  当前循环次数
$x@total     总循环次数
$x@first  循环第一次
$x@last     循环最后一次
新的foreach语法

{foreach $myarray as $var}...{/foreach}
同样是foreach里头的特殊表示符,看的就明白,不翻译了……

$var@key            foreach $var array key
$var@iteration      foreach current iteration count (1,2,3...)
$var@index          foreach current index count (0,1,2...)
$var@total          foreach $var array total
$var@first          true on first iteration
$var@last           true on last iteration
支持while循环

{while $foo}...{/while}
{while $x lt 10}...{/while}
可以直接使用PHP的函数

{time()}
新增加了一个{function}的标签,可以定义一个可供调用的函数块(我喜欢这功能,哈哈!)

{function}...{/function}
该标签必须有一个name属性,用来指名该函数名称,也是调用的时候需要用到的

下面是一个例子

/* 定义一个函数 */
{function name=menu level=0}
    <ul>
    {foreach $data as $entry}
        {if is_array($entry)}
            <li>{$entry@key}</li>
            {menu data=$entry level=$level+1}
        {else}
            <li>{$entry}</li>
        {/if}
    {/foreach}
    </ul>
{/function}

/* 给函数传递的参数 */
{$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
    ['item3-3-1','item3-3-2']],'item4']}

/* 调用那个函数 */
{menu data=$menu}
{function}功能函数必须有一个name属性,并且可以拥有任意多个的其它属性

代码块不缓存,可以使用{nocache}标签默认是关闭的

{nocache} ... {/nocache}
还可以作为属性

{$foo nocache=true}
{$foo nocache}
{foo bar="baz" nocache=true}
{foo bar="baz" nocache}
{time() nocache=true}
{time() nocache}
返回当前模板的方法

$smarty.cur_template
变量作用域和存储
在Smarty2中,所有的变量都存储在Smarty对象中,因此所有的变量在所有模板和子方法中都可以获取

在Smarty3中,可以自己定义的将变量存储在主Smarty对象中,或者用户自己定义的对象中,甚至是用户自己的模板对象中

而且这些对象可以通过链式串接起来。

在链的末尾的对象可以获取到对象链之前的对象中存储的所有变量。

Smarty对象必须是链的根对象,但是对象链却是可以独立于Smarty对象存在的

所有的Smarty的赋值方法都可以用在data对象或者模板对象

除了上面说几个方面,全局变量还有一种特殊的存储方式

一个Smarty的数据对象(data Object)可以通过如下方式创建

$data = $smarty->createData();    // 创建根数据对象
$data->assign('foo','bar');       // 赋值操作
$data->config_load('my.conf');      // 加载配置文件

$data = $smarty->createData($smarty);   // 以Smarty作为父对象,创建数据对象

$data2= $smarty->createData($data);     // 以data作为父对象,创建数据对象data2
创建一个模板对象(template object) 可以通过createTemplate方法,它的参数传递和fetch()/display()方法一致

函数定义方式

function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null)
举例

$tpl = $smarty->createTemplate('mytpl.tpl'); // 创建一个模板对象,没有父对象
$tpl->assign('foo','bar');                   // directly assign variables
$tpl->config_load('my.conf');

$tpl = $smarty->createTemplate('mytpl.tpl',$smarty); // 以Smarty为父对象,创建模板对象
fetch()/display() 两个方法将隐式的创建一个模板对象

如果不指定父对象,则默认父对象将指向Smarty对象

如果一个模板是通过include方式调用的,则子模板的父对象将指向引用它的模板对象

所有当前模板变量和父对象的模板变量都是可以获取的,但是如果是通过{assign}或者{$foo=…}这样的方法创建或者修改变量

则它的作用域将只停留在当前模板对象

Smarty3中,在赋值变量的时候可以指定它的作用域,有4个值local,parent,root,global

{assign var=foo value='bar'}       // no scope is specified, the default 'local'
{$foo='bar'}                       // same, local scope
{assign var=foo value='bar' scope='local'} // same, local scope
{assign var=foo value='bar' scope='parent'} // Values will be available to the parent object
{$foo='bar' scope='parent'}                 // (normally the calling template)
{assign var=foo value='bar' scope='root'}   // Values will be exported up to the root object, so they can
{$foo='bar' scope='root'}                   // be seen from all templates using the same root.
{assign var=foo value='bar' scope='global'} // Values will be exported to global variable storage,
{$foo='bar' scope='global'}
扩展
Smarty3的扩展都是继承至Smarty – Internal – PluginBase的类

所有的扩展都包含一个Smarty对象实例的$this->smarty属性

模板继承
你可以在模板中写{block} … {/block}快,并且这些块可以在子模板中进行覆盖

parent.tpl:

<html>
    <head>
        <title>{block name='title'}My site name{/block}</title>
    </head>
    <body>
        <h1>{block name='page-title'}Default page title{/block}</h1>
        <div id="content">
            {block name='content'}
            Default content
            {/block}
        </div>
    </body>
</html>
child.tpl:

{extends file='parent.tpl'}

{block name='title'}
    Child title
{/block}
grandchild.tpl:

{extends file='child.tpl'}

{block name='title'}Home - {$smarty.block.parent}{/block}
{block name='page-title'}My home{/block}
{block name='content'}
    {foreach $images as $img}
        <img src="{$img.url}" alt="{$img.description}" />
    {/foreach}
{/block}
可以通过extends标签来指定被继承的模板,并在子模板中通过重写父模板的同名block块,达到覆盖的目的

同时,可以通过{$smarty.block,parent}获取到父block的内容

上面的grandchild.tpl将生成如下内容

<html>
    <head>
        <title>Home - Child title</title>
    </head>
    <body>
        <h1>My home</h1>
        <div id="content">
            <img src="/example.jpg" alt="image" />
            <img src="/example2.jpg" alt="image" />
            <img src="/example3.jpg" alt="image" />
        </div>
    </body>
</html>
注意,在子模板中,所有在{block} … {/block}之外的内容都将被忽略

这种继承支持多文件,多重继承,意味着可以无线的继承下去

还可通过{block}的append和prepend属性来插入父模板结构中

PHP 流
待补充…

变量过滤
待补充…

PHP 模板
对于那些希望在模板中纯粹写PHP的人员来说,Smarty提供了一个php的选项,纯PHP和有以下几个不同的地方:

1.PHP模板将不进行编译,直接被引擎调用
2.PHP模板将不具备任何安全属性
3.Smarty默认不开启PHP模板,可以$smarty->allow_php_templates=true来打开
如果你想使用php模板,只需要使用php资源类型

$smarty->display('php:foo.php');
你还可以在模板里头混合着用

{include file="php:foo.php"}

JS三目运算(三元运算)方法详解 1、什么是三目运算:(布尔表达式 ? 值0:值1;) 5>3?alert(‘5大’):alert(‘3大’); 即    if(5>3){alert(‘5大’)}else{alert(‘3大’)}; 注意:三目运算和if(){}else{}的 区别是三目运算有返回值 例如: var max = a>b?a:b; 2、多条件的三目运算怎么写: 实例:根据学生成绩判定ABCD四个等级 var result = (sc<0>100) ?(“分数无效”): sc>=90?(“A”):   sc>=80?(“B”):    sc>=60?(“C”):(“D”); 注意: 计算时需考虑优先级问 立即下载

相关推荐

Smarty模板语法详解

主要介绍了Smarty模板语法,结合实例形式详细分析了Smarty模板的注释、变量、引号、函数等基本语法与使用技巧,需要的朋友可以参考下

使用"模板驱动方式"简化开发 ----smarty插件的使用

原贴:http://phpx.com/happy/showthread.php?s=&amp;threadid=96819     使用"模板驱动方式"简化开发 ----smarty插件的使用     关键词: 模板, smarty, 插件, PHP   作  者: 李晓军 (大师兄)   Email:  teacherli@163.com   MSN:    teacherli@ceua.org...

泡泡还是泡泡,本博客属于个人收藏 255

php中smarty模板条件判断用法实例

主要介绍了php中smarty模板条件判断用法,实例分析了smarty模板条件判断的使用技巧,需要的朋友可以参考下

tp3.2 中smaty模板使用三目运算的方法

例如 {($a==1)?"a":"c"} 细节在于吧式子加上括号,要不然会报错。

两眼红光 2028

KEIL-MDK代码美化神器:AStyle配置全攻略(附常用参数详解)

本文详细介绍了如何在KEIL-MDK中配置和使用AStyle代码格式化工具,包括基础参数设置、高级格式控制、团队协作方案以及KEIL深度集成技巧。通过合理的AStyle配置,开发者可以显著提升代码风格一致性,优化团队协作效率,特别适合嵌入式开发项目。

weixin_30505225的博客 146

从零理解域随机化:通过Isaac Lab的events.py掌握Sim-to-Real关键技术

本文深入解析域随机化技术如何通过Isaac Lab的events.py实现Sim-to-Real迁移,提升机器人策略在真实世界的鲁棒性。从刚体属性到环境条件的系统级随机化,详细介绍了工程实践中的关键参数配置与调试技巧,帮助开发者有效缩小仿真与现实的差距。

weixin_29062613的博客 260

smarty3.0 体验 赠送手册

Smarty3.0 初步认识 今天想通过用Smarty作一个东东,准备到官网去下一个最新的版本下来。 没曾想Smarty出了3.0版本了,目前还处在beta阶段,已经到beta8了 当下弄下来折腾一下,看看有什么好东西 这里大概解读一下附带的README文件 BETA8 需要注意的事情 Smarty3 的API已经被重构过以更好的面向结构话和语法一致性。但是Smarty2的API仍然是...

xubaoguo196的专栏 197

【实验】Linux下完全卸载oracle单实例(亲身体验完整版)

停止oracle数据库服务 停止监听 卸载数据库实例 因为自己懒得再弄dbca图形化界面啥的,直接采用dbca静默删除数据库实例,命令如下 dbca -silent -deleteDatabase -sourcedb orclhq -sid orcl -sysDBAUserName orcl -sysDBAPassword zte [oracle@slave ~]$ dbca -silent ...

萝卜吃鱼914的博客 1945

模板中支持三元运算 不能用点

模板中可以支持简单的变量三元运算符,例如: {$vo['status']>0?'正常':'禁用'} 三元运算符中的条件变量必须使用php语法,不支持点语法。

大任的网络专栏 5427

Jenkins+docker 微服务实现自动化部署安装和部署过程

本文详细介绍了如何使用Docker部署Jenkins自动化服务器。主要内容包括:1)拉取Jenkins官方或BlueOcean镜像;2)创建容器并配置端口映射、数据卷挂载;3)设置防火墙规则;4)配置清华大学镜像加速;5)安装必要插件;6)SSH密钥配置;7)构建触发器设置;8)编写自动化构建脚本。通过Docker部署Jenkins可以简化安装流程,确保环境一致性,并利用容器特性实现快速启动和管理。文章提供了完整的配置步骤和注意事项,帮助用户快速搭建CI/CD环境。

qq_33665793的博客 1687

GPU架构-SIMT

本文深度剖析了GPU的SIMT架构,从硬件实现层面解析其与SIMD的本质差异。SIMT通过将32个线程捆绑为warp执行,在标量编程模型下实现数据并行。文章对比了SIMD和SIMT的执行模型、分支处理机制及存储层次,指出SIMT是对SIMD的虚拟化抽象。重点分析了Volta架构引入的独立线程调度技术,以及访存合并对性能的关键影响。通过定量数据展示了各代GPU架构的寄存器文件规模和线程调度机制,为开发者优化GPU程序提供了硬件层面的理论基础。

技术引领业务创新 973

在smarty模板中调用PHP自定义函数(从smarty2到smarty3)

 这两天研究了一下smarty,熟悉了它的一些基本语法后便开始用它开发一个留言版(真正的开发中一般不会有程序员使用smarty去开发一个留言版的,杀鸡焉用牛刀?),主要是为了将所学的知识点串联起来。在开发的过程中,遇到了一个问题,如题,我在PHP文件中定义了一个函数,现在想在.tpl模版中调用,该如何调用呢?通过在网上查找一些资料,下面给出具体的解决方案:大家都知道,在smarty中提供了

huli870715的专栏 1万+

【UE5】【蓝图】 LevelSequence 动画播放与暂停

最近有些工作,在研究UE5 蓝图的LevelSequence,来制作一些简单动画。做个笔记,记录一下动画更换绑定actor的操作,以及动画播放后如何暂停和继续。

UE5开发备忘录 1万+

smarty3的一些实用的新特性

BETA8 需要注意的事情 Smarty3 的API已经被重构过以更好的面向结构话和语法一致性。但是Smarty2的API仍然是支持的,但是会出提示。 当然,也可以手动disable掉这个提示,但是强烈推荐你将你的语法升级到适应Smarty3的语法 Smarty3中所有的方法命名都采用”fooBarBaz”的方式,而且,所有的Smarty属性都含有getters和setters,举例: 老

吸星大法--吸百家武学之精华。大成也 1060

Spring Boot整合Apache Hop 2.3.0实战:从零搭建数据管道(附完整代码)

本文详细介绍了如何在Spring Boot项目中整合Apache Hop 2.3.0,从零开始构建可嵌入的数据管道。内容涵盖环境初始化、依赖配置、管道设计,并通过完整代码示例演示了如何通过REST API触发执行,实现数据同步与ETL流程的自动化管理,为微服务架构提供灵活的数据集成方案。

web99的专栏 632

AgentScope 2.0 扩展开发完全指南:从中间件到模型适配器的深度实践

本文系统讲解 AgentScope 2.0 框架的五大扩展机制,涵盖中间件系统的洋葱模型与钩子设计、ChatModelBase 基类与多供应商适配器开发、工作空间(本地/Docker/E2B)的抽象接口与生命周期管理、凭据工厂与 MCP 协议集成、以及工具协议与存储后端扩展。文中提供完整的架构图、代码示例与故障排查指南,帮助开发者快速掌握 AgentScope 的插件化扩展体系。

program哲学 296

smarty 模板php,PHP 模板之Smarty 模板介绍

一、Smarty 简介Smarty 是 PHP 中的一个模板引擎,是众多 PHP 模板中最优秀、最著名的模板之一。1、什么是SmartySmarty 是一个使用 PHP 编写的 PHP 模板引擎,它将一个应用程序分成两个部分实现:视图和逻辑控制。简单地讲,目的就是将 UI(用户界面)和 PHP code(PHP代码)分离。这样,程序员在修改程序时不会影响的页面设计,而美工在重新设计或是修改页面时也...

weixin_36268722的博客 477

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

php smarty框架案例,php封装的smarty类案例

这篇文章主要介绍了php封装的smarty类,针对Smarty的基本操作技巧进行了封装整理,具有一定参考借鉴价值,需要的朋友可以参考下具体如下:/*** Project: Smarty: the PHP compiling template engine* File: Smarty.class.php* SVN: $Id: Smarty.class.php 4848 2014-0...

weixin_31640385的博客 514

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

smarty2 php,Smarty2至Smarty3升级指南.

Smarty2和Smarty3在告终上差不多,然而在smarty2升级到smarty3的时候还是要当心些许不同。下面是已知的和smarty2不接受的地方== 语法 ==Smarty 3 API有些方面举行了更新。一些Smarty 2 API调用必需更新以便相称Smarty3。你可能会获得提醒,评比你利用新的语法。能够察看Smarty 3附带的 README 文件获得更多消息。{$array|@mo...

weixin_39718083的博客 259

在smarty模板中调用PHP自定义函数(从smarty2到smarty3)【转】

http://blog.youkuaiyun.com/huli870715/article/details/6526268这两天研究了一下smarty,熟悉了它的一些基本语法后便开始用它开发一个留言版(真正的开发中一般不会有程序员使用smarty去开发一个留言版的,杀鸡焉用牛刀?),主要是为了将所学的知识点串联起来。在开发的过程中,遇到了一个问题,如题,我在PHP文件中定义了一个函数,现在想在.tpl模版中调

后端开发 828

php smarty extends,php封装的smarty类完整实例

本文实例讲述了php封装的smarty类。分享给大家供大家参考,具体如下:/*** Project: Smarty: the PHP compiling template engine* File: Smarty.class.php* SVN: $Id: Smarty.class.php 4848 2014-06-08 18:12:09Z Uwe.Tews@googlemail....

weixin_32537261的博客 293

PHP学习笔记6——Smarty模板引擎

PHP学习笔记3——Smarty模板引擎模板引擎的工作原理1. PDO读取学生信息2. 如何实现PHP 代码和HTML代码分离3.如何彻底去除视图文件中的PHP标记常用的PHP模板引擎Smarty入门什么是Smarty快速入门案例Smarty的常用配置左右定界符Smarty常用目录的配置(1)设置或读取视图文件目录(2)其他目录的设置和读取方法Smarty中的变量1. 普通变量2.保留变量(1)访...

DonkeyL's 831

php之smarty框架

一、smarty框架的使用步骤         1.下载smarty,并将此文件夹放在所需的目录下          2.引入Smarty.class.php(注意大小写)          3.定义smarty所使用的文件目录,并且实例化对象          4.指定模板文件所在的路经          5.指定模板编译后的文件所在路经          6.向模板传递变量   ...

weidandan520的博客 908

php smarty安装,Smarty安装

Smarty手册范例 2-5.手工设置SMARTY_DIR常量define('SMARTY_DIR','/usr/local/lib/php/Smarty/');require(SMARTY_DIR.'Smarty.class.php');$smarty = new Smarty;现在库文件已经搞定,该是设置为你的应用程序配置其他有关Smarty的目录的时候了。Smarty要求4个目录,默认下命名...

weixin_34404808的博客 318
上一篇: php学习笔记(四十)smarty3的模板继承新特性
下一篇: ant笔记(二)ant的属性使用与引用外部变量,集成一个编译,拷贝,打包,运行的任务链
阳小良
博客等级 码龄17年 54粉丝 155原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值