服务器脚本

Silk可以作为脚本语言嵌入任何文本中,包括HTML网页,配置文件等,所以可以像PHP,ASP,Perl等语言一样作为服务器端脚本运行,生成动态网页。
Silk脚本可以放在文本中的任何位置,以标记 <?silk 开始,以 ?> 结束。
Silk只会执行标记之内的代码,最终将会产生标记之外的HTML内容和代码执行结果的混合内容:
<!DOCTYPE html>
<html>
<body>

<h1>My first Silk page</h1>

<?silk
    response.write("Hello World");
?>   

</body>
</html>  

Silk会忽略不满足条件的内容块,即使这些内容在标记之外:
<!DOCTYPE html>
<html>
<body>

<?silk
    hour=_fun("time_now")["hour"];
?>

<?silk if (hour<10) ?>
  <h>Good morning.</h>
<?silk else {?>
  <h>Hello,</h>
  <br/>
  <h>It's a nice day.</h>
<?silk } ?>

<?silk 
//Silk脚本甚至可以像下面这样嵌入在HTML的tag里:
 ?>
 <p<?silk if (hour>12){ ?> style="color: rgb(255, 0, 0);"<?silk }?>>Good afternoon.</p>

</body>
</html>

response是Silk脚本内置的类对象,它有一个属性content和一个方法write,用来获取对象的内容和向对象写内容。
Silk脚本执行完毕后默认将返回response的内容,response对象的内容包含HTML的内容和通过write方法加入的内容,也就是整个动态网页的内容。

<!DOCTYPE html>
<html>
<body>

<h1>My Silk page</h1>

<?silk
    hour=_fun("time_now")["hour"];
    if (hour<10)
    {
        response.write("Good Morning!");
    }
    else if (hour<20)
    {
        response.write("Good Day!");
    }
    else
    {
        response.write("Good night!");
    }
?>   

</body>
</html>  

上面的例子如果是在上午10点前执行,会得到如下的网页内容:

<!DOCTYPE html>

<html>

<body>

<h1>My Silk page</h1>

Good Morning!   

</body>

</html>  

response对象可以写任何字符串内容,包括HTML标签,遇到双引号等特殊字符需使用转义符\:
<!DOCTYPE html>
<html>
<body>
<?silk
response.write(sprintf("<h2>%s!</h2>","this is a title"));
?>

<?silk
response.write("<p style=\"color:#0000ff\">This text is styled with the style attribute!</p>");
?>
</body>
</html>

如果脚本执行中途需停止执行而退出,可以直接通过返回response的content属性返回,后面的内容包括HTML内容将不被输出:
<!DOCTYPE html>
<html>
<body>
<?silk
    return response.content;
?>
<?silk
response.write("<p style=\"color:#0000ff\">This text is styled with the style attribute!</p>");
?>
</body>
</html>
上面脚本将只会输出如下不完整的网页内容:
<!DOCTYPE html>
<html>
<body>

也可以忽略response对象直接返回字符串:
<!DOCTYPE html>
<html>
<body>
<?silk
    return "Hello";
?>
</body>
</html>
输出内容如下:
Hello

脚本文件(Silk Server Page, .ssp文件)的执行需通过内置函数_fun("runfile_tag", filename, outputFile, args)
filename为脚本文件,outputFile为把运行结果写入outputFile文件中,如果无需写入文件,就传入空字符串。
args为传入脚本的参数,必须为字典对象,
用以和被执行脚本代码进行交互。
#!C:\Silk\Silk.exe

#include "cgi.si"

main()
{
    printf("Content-type:text/html\n\n");//header
    
    env=get_envs();
    args={};
    args["ENV"]=env;
    
    html=_fun("runfile_tag","page.ssp","",args);
    printf(html);
}
上面CGI程序将会执行page.ssp脚本,把执行后生成的动态网页内容返回给Apache服务器,再由服务器返回给客户端浏览器。

更多例子请参考安装包里的CGI例程。
也可参考安装包里的HttpServer例程,HttpServer是完全由Silk编写的多线程HTTP服务器,不需要依赖任何其它服务器即可运行和测试Silk脚本。