How to choose template engine

前言

后端渲染页面的开发方式目前还占据着主导的地位,虽然像Backbone、Angular、Reactjs等技术很火,但是在国内的普及和应用还远远不够。单页,前端渲染页面的方式想要成为主流还有很长的路要走。在我接触的语言中,后端开发的模式基本以MVC为主,V当然所谓的View了,如Java的Jsp、Velocity、Freemark,再如Node的Ejs、Jade、Handlebars等等,可以说不同语言对应很多的模板引擎,那么我们该如何选择模板引擎呢?我从实际开发的维护性来谈几点。

Layouts

使用layouts可以抽出我们页头的公共代码,使我们只需关注单个页面的内容。一般的Html页面都是这样的

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>title</title>       
    <link rel="stylesheet" href="css/bootstrap.css"/>
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="container" id="container"></div>
</body>
</html>

如果不使用layouts,每个页面我们都得复制一遍上面的代码,然后改变body里的内容,如果有十个页面我们就得复制十遍,更别说复杂的应用了页面都是几十往上。想想这样的情景:你维护着没使用layouts的应用,大概一百左右的页面吧,有一天需要在header里加一个meta标签...别说做了,想想我就想吐了。使用了layouts维护起来就像这样的

#default.xx
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>title</title>       
    <link rel="stylesheet" href="css/bootstrap.css"/>
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
    {body}
</body>
</html>

#index.xx
<div class="container" id="container"></div>

Partials

partials和layouts的核心都是抽出相同的代码,便于维护。比如页面有一个公共的footer结构,98%的页面需要这个结构,剩下的页面不需要。不使用partials的话,就看看哪些页面需要,然后后一个个复制粘贴,好不容易复制完了,设计跑来说:不好意思哈,刚footer里一个标签使用错了,把span改成div。丫的还得一个个去改,累死累活完成了,设计又跑过来了:那啥,还是改回span吧。估计那会儿不管是谁,心里都会默念草泥马。大把的时间都浪费在复制粘贴反复修改上面了。使用了partials,需要footer的页面就引一下,就像这样

#footer.xx
<div>footer</div>

#index.xx
<div>content</div>
{include footer}

这个时候footer里随便改啥都轻松搞定,因为只需要维护一份代码

Block

Block可以理解为占位符,例如上面的layouts default.xx只有一份代码,title是固定的,那么渲染出来每个页面的title都是相同的。实际上不同的页面title是不同的,那么怎么办?有人会说了,title通过后端传递值。我个人觉得页面级的内容最好不要丢到后端去维护,会造成后端代码的冗余,不能为了渲染而渲染。这个时候我们就需要Block了。

#default.xx
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{title}</title>     
    <link rel="stylesheet" href="css/bootstrap.css"/>
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
    {body}
</body>
</html>

#page1.xx
{define title 'page1'}
<div>page1 content</div>

#page2.xx
{define title 'page2'}
<div>page2 content</div>

其实就是占个坑,然后在具体的页面里指定内容。

Marco

在模板中调用工具方法,举一个最常见的例子,日期格式化,如果在模板中使用不了工具方法。那么我们就得在后端的逻辑代码中先格式化时间,虽然能抽出一个公共的方法调用,但是我还是觉得不能为了渲染而渲染,将这些渲染逻辑丢到业务中。如果模板支持宏,拿上面的例子来说就像这样

#index.xx
{format time 'YYYY-MM-DD'}
<div>page1 content</div>

Set

前面四个内容我觉得是一个模板引擎的标配,随便少了哪样,都会使维护性变得更差,除非有其他类似的替代方案。至于现在的set其实就是可以在模板中声明变量,并可以进行简单的逻辑判断,变量声明这个功能很多模板是不支持的。那么有什么具体的作用呢?拿上面的footer的例子来说,虽然只有2%的页面不需要footer,我们仍然没办法将footer放进layouts中,因为放进layouts中意味着所有的页面都出现footer,当然了你可以说服你的产品经理或者交互工程师,要求所有的页面的都添加footer。可惜这样完美的情况是少数的,我们还得在98%的页面中添加下面一段代码

{include footer}

如果哪天footer改名了,你知道怎么做了吧...如果模板引擎支持变量声明和逻辑判断,那么可以试着这么干

#default.xx
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{title}</title>     
    <link rel="stylesheet" href="css/bootstrap.css"/>
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
    {body}
    {if !noFooter}
        {include footer}
    {endif}
</body>
</html>

#sb.xx
{set noFooter=true}
<div>劳资就不要footer</div>

顿时妈妈再也不用担心文件改名了。

小结

撇开性能暂且不谈,无论什么样的模板引擎,都应该大大简化我们的工作。如果使用了模板引擎,对页面管理和代码组织毫无用处,那离死也就不远了!

Google Cloud Tools¶ Google Cloud tools make it easier to connect your agents to Google Cloud’s products and services. With just a few lines of code you can use these tools to connect your agents with: Any custom APIs that developers host in Apigee. 100s of prebuilt connectors to enterprise systems such as Salesforce, Workday, and SAP. Automation workflows built using application integration. Databases such as Spanner, AlloyDB, Postgres and more using the MCP Toolbox for databases. Google Cloud Tools Apigee API Hub Tools¶ ApiHubToolset lets you turn any documented API from Apigee API hub into a tool with a few lines of code. This section shows you the step by step instructions including setting up authentication for a secure connection to your APIs. Prerequisites Install ADK Install the Google Cloud CLI. Apigee API hub instance with documented (i.e. OpenAPI spec) APIs Set up your project structure and create required files project_root_folder | `-- my_agent |-- .env |-- __init__.py |-- agent.py `__ tool.py Create an API Hub Toolset¶ Note: This tutorial includes an agent creation. If you already have an agent, you only need to follow a subset of these steps. Get your access token, so that APIHubToolset can fetch spec from API Hub API. In your terminal run the following command gcloud auth print-access-token # Prints your access token like 'ya29....' Ensure that the account used has the required permissions. You can use the pre-defined role or assign the following permissions:roles/apihub.viewer apihub.specs.get (required) apihub.apis.get (optional) apihub.apis.list (optional) apihub.versions.get (optional) apihub.versions.list (optional) apihub.specs.list (optional) Create a tool with . Add the below to APIHubToolsettools.py If your API requires authentication, you must configure authentication for the tool. The following code sample demonstrates how to configure an API key. ADK supports token based auth (API Key, Bearer token), service account, and OpenID Connect. We will soon add support for various OAuth2 flows. from google.adk.tools.openapi_tool.auth.auth_helpers import token_to_scheme_credential from google.adk.tools.apihub_tool.apihub_toolset import APIHubToolset # Provide authentication for your APIs. Not required if your APIs don't required authentication. auth_scheme, auth_credential = token_to_scheme_credential( "apikey", "query", "apikey", apikey_credential_str ) sample_toolset_with_auth = APIHubToolset( name="apihub-sample-tool", description="Sample Tool", access_token="...", # Copy your access token generated in step 1 apihub_resource_name="...", # API Hub resource name auth_scheme=auth_scheme, auth_credential=auth_credential, ) For production deployment we recommend using a service account instead of an access token. In the code snippet above, use and provide your security account credentials instead of the token.service_account_json=service_account_cred_json_str For apihub_resource_name, if you know the specific ID of the OpenAPI Spec being used for your API, use . If you would like the Toolset to automatically pull the first available spec from the API, use `projects/my-project-id/locations/us-west1/apis/my-api-id/versions/version-id/specs/spec-id``projects/my-project-id/locations/us-west1/apis/my-api-id` Create your agent file Agent.py and add the created tools to your agent definition: from google.adk.agents.llm_agent import LlmAgent from .tools import sample_toolset root_agent = LlmAgent( model='gemini-2.0-flash', name='enterprise_assistant', instruction='Help user, leverage the tools you have access to', tools=sample_toolset.get_tools(), ) Configure your `__init__.py` to expose your agent from . import agent Start the Google ADK Web UI and try your agent: # make sure to run `adk web` from your project_root_folder adk web Then go to http://localhost:8000 to try your agent from the Web UI. Application Integration Tools¶ With ApplicationIntegrationToolset you can seamlessly give your agents a secure and governed to enterprise applications using Integration Connector’s 100+ pre-built connectors for systems like Salesforce, ServiceNow, JIRA, SAP, and more. Support for both on-prem and SaaS applications. In addition you can turn your existing Application Integration process automations into agentic workflows by providing application integration workflows as tools to your ADK agents. Prerequisites Install ADK An existing Application Integration workflow or Integrations Connector connection you want to use with your agent To use tool with default credentials: have Google Cloud CLI installed. See installation guide. Run: gcloud config set project <project-id> gcloud auth application-default login gcloud auth application-default set-quota-project <project-id> Set up your project structure and create required files project_root_folder |-- .env `-- my_agent |-- __init__.py |-- agent.py `__ tools.py When running the agent, make sure to run adk web in project_root_folder Use Integration Connectors¶ Connect your agent to enterprise applications using Integration Connectors. Prerequisites To use a connector from Integration Connectors, you need to provision Application Integration in the same region as your connection by clicking on "QUICK SETUP" button. Google Cloud Tools Go to Connection Tool template from the template library and click on "USE TEMPLATE" button. Google Cloud Tools Fill the Integration Name as ExecuteConnection (It is mandatory to use this integration name only) and select the region same as the connection region. Click on "CREATE". Publish the integration by using the "PUBLISH" button on the Application Integration Editor. Google Cloud Tools Steps: Create a tool with ApplicationIntegrationToolset from google.adk.tools.application_integration_tool.application_integration_toolset import ApplicationIntegrationToolset connector_tool = ApplicationIntegrationToolset( project="test-project", # TODO: replace with GCP project of the connection location="us-central1", #TODO: replace with location of the connection connection="test-connection", #TODO: replace with connection name entity_operations={"Entity_One": ["LIST","CREATE"], "Entity_Two": []},#empty list for actions means all operations on the entity are supported. actions=["action1"], #TODO: replace with actions service_account_credentials='{...}', # optional tool_name="tool_prefix2", tool_instructions="..." ) Note: - You can provide service account to be used instead of using default credentials. - To find the list of supported entities and actions for a connection, use the connectors apis: listActions or listEntityTypes Add the tool to your agent. Update your fileagent.py from google.adk.agents.llm_agent import LlmAgent from .tools import connector_tool root_agent = LlmAgent( model='gemini-2.0-flash', name='connector_agent', instruction="Help user, leverage the tools you have access to", tools=connector_tool.get_tools(), ) Configure your `__init__.py` to expose your agent from . import agent Start the Google ADK Web UI and try your agent. # make sure to run `adk web` from your project_root_folder adk web Then go to http://localhost:8000, and choose my_agent agent (same as the agent folder name) Use App Integration Workflows¶ Use existing Application Integration workflow as a tool for your agent or create a new one. Steps: Create a tool with ApplicationIntegrationToolset integration_tool = ApplicationIntegrationToolset( project="test-project", # TODO: replace with GCP project of the connection location="us-central1", #TODO: replace with location of the connection integration="test-integration", #TODO: replace with integration name trigger="api_trigger/test_trigger",#TODO: replace with trigger id service_account_credentials='{...}', #optional tool_name="tool_prefix1", tool_instructions="..." ) Note: You can provide service account to be used instead of using default credentials Add the tool to your agent. Update your fileagent.py from google.adk.agents.llm_agent import LlmAgent from .tools import integration_tool, connector_tool root_agent = LlmAgent( model='gemini-2.0-flash', name='integration_agent', instruction="Help user, leverage the tools you have access to", tools=integration_tool.get_tools(), ) Configure your `__init__.py` to expose your agent from . import agent Start the Google ADK Web UI and try your agent. # make sure to run `adk web` from your project_root_folder adk web Then go to http://localhost:8000, and choose my_agent agent (same as the agent folder name) Toolbox Tools for Databases¶ MCP Toolbox for Databases is an open source MCP server for databases. It was designed with enterprise-grade and production-quality in mind. It enables you to develop tools easier, faster, and more securely by handling the complexities such as connection pooling, authentication, and more. Google’s Agent Development Kit (ADK) has built in support for Toolbox. For more information on getting started or configuring Toolbox, see the documentation. GenAI Toolbox Configure and deploy¶ Toolbox is an open source server that you deploy and manage yourself. For more instructions on deploying and configuring, see the official Toolbox documentation: Installing the Server Configuring Toolbox Install client SDK¶ ADK relies on the python package to use Toolbox. Install the package before getting started:toolbox-langchain pip install toolbox-langchain langchain Loading Toolbox Tools¶ Once you’ve Toolbox server is configured and up and running, you can load tools from your server using the ADK: from google.adk.tools.toolbox_tool import ToolboxTool toolbox = ToolboxTool("https://127.0.0.1:5000") # Load a specific set of tools tools = toolbox.get_toolset(toolset_name='my-toolset-name'), # Load single tool tools = toolbox.get_tool(tool_name='my-tool-name'), root_agent = Agent( ..., tools=tools # Provide the list of tools to the Agent ) Advanced Toolbox Features¶ Toolbox has a variety of features to make developing Gen AI tools for databases. For more information, read more about the following features: Authenticated Parameters: bind tool inputs to values from OIDC tokens automatically, making it easy to run sensitive queries without potentially leaking data Authorized Invocations: restrict access to use a tool based on the users Auth token OpenTelemetry: get metrics and tracing from Toolbox with OpenTelemetry帮我画一张思维导图
05-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值