3

我在另一篇文章中看到了一种非常手动的方法:如何将查询参数添加到 URL?

这似乎不是很直观,但有人提到了一种更简单的方法来使用即将推出的“URL 范围”来实现这一点。这个功能还没有,我将如何使用它?

4

2 回答 2

2

如果您使用的是 stdlib 混合器,您应该能够使用 URL 范围,它提供了用于添加、查看、编辑和删除 URL 参数的辅助函数。这是一个简单的例子:

$original_url = "http://cuteoverload.com/2013/08/01/buttless-monkey-jams?hi=there"
$new_url = url($original_url) {
  log(param("hi"))
  param("hello", "world")
  remove_param("hi")
}
log($new_url)

氚测试仪示例:http: //tester.tritium.io/9fcda48fa81b6e0b8700ccdda9f85612a5d7442f

差点忘了,文档链接: http: //tritium.io/current(您需要单击 URL 类别)。

于 2013-08-02T07:28:37.707 回答
0

AFAIK,没有内置的方法。我将在这里发布我是如何附加查询参数的,如果它已经在 url 上,请确保它不会被重复:

在您的 functions/main.ts 文件中,您可以声明:

# Adds a query parameter to the URL string in scope.
# The parameter is added as the last parameter in
# the query string.
#
# Sample use:
# $("//a[@id='my_link]") {
#   attribute("href") {
#     value() {
#       appendQueryParameter('MVWomen', '1')
#     }
#   }
# }
#
# That will add MVwomen=1 to the end of the query string,
# but before any hash arguments.
# It also takes care of deciding if a ? or a #
# should be used.
@func Text.appendQueryParameter(Text %param_name, Text %param_value) {
    # this beautiful regex is divided in three parts:
    #   1. Get anything until a ? or # is found (or we reach the end)
    #   2. Get anything until a # is found (or we reach the end - can be empty)
    #   3. Get the remainder (can be empty)
    replace(/^([^#\?]*)(\?[^#]*)?(#.*)?$/) {
        var('query_symbol', '?')
        match(%2, /^\?/) {
            $query_symbol = '&'
        }

        # first, it checks if the %param_name with this %param_value already exists
        # if so, we don't do anything
        match_not(%2, concat(%param_name, '=', %param_value)) {

            # We concatenate the URL until ? or # (%1),
            # then the query string (%2), which can be empty or not,
            # then the query symbol (either ? or &),
            # then the name of the parameter we are appending,
            # then an equals sign,
            # then the value of the parameter we are appending
            # and finally the hash fragment, which can be empty or not
            set(concat(%1, %2, $query_symbol, %param_name, '=', %param_value, %3))
        }       
    }
}

您想要的其他功能(删除、修改)可以类似地实现(通过在 functions/main.ts 中创建一个函数并利用一些正则表达式魔法)。

希望能帮助到你。

于 2013-08-01T23:25:31.313 回答